Friday, June 19, 2009

Misc: a 3D skull model.


Created with Blender.

Tuesday, June 16, 2009

Matlab: find row vector within matrix.

OP here.

Q:

Say I have a matrix:

x = [
11 22 33
44 55 66
11 11 11
33 99 33
11 77 23]


I want to find a specific row in it, say y = [11 11 11].


A1:
You can use ismember with parameter "rows".

A2:
To allow some tolerance:

% engine;
locrow = @(A,x,tol)find(sum(abs(bsxfun(@minus,A,x)),2) <= tol)

% usage;
tol = 0.01
locrow(A,[11.0001, 11.0001, 10.9999], tol)

Matlab: vectorize a loop that depends on past info.

OP here.

Q:

Can anybody think of a vectorized solution to the problem below? suppose x(1) ~= 0;

for k = 2:length(x)
if x(k) == 0
x(k) = x(k-1);
end
end


A:

y = find(x);
x1 = x(y(cumsum(x ~= 0)));



Note:
In most cases the for-loop is probably 3-4 times faster than the vectorized code.

Matlab: vector indexing.

OP here.

Q:
I have a random vector r of size 50000 x 1, and a strictly decreasing measuring vector d of size 300 x 1. I want for each element in r, find the indices of the first value in d that is smaller than it. I tried these codes but it is too slow. Is there a vectorized solution?

n = 50000;
r = rand(n,1);
d = linspace(1,0,300);
idx = nan(n,1);

for k = 1:n
idx(k) = find(r(k) > d, 1, 'first');
end


A:

[dump,idx] = histc(r,d(end:-1:1));
idx = length(d)-idx+1;

Wednesday, June 10, 2009

Matlab: break consecutive numbers into cells

OP here.


Q:

Suppose I have a sorted array like

[1 2 3 4 5 10 11 17 18 19]


I want to break consecutive blocks into separate arrays:

[1 2 3 4 5]
[10 11]
[17 18 19]


A:

mat2cell(x,1,diff([0,find(diff(x) ~= 1),length(x)]))

Tuesday, June 09, 2009

Matlab: find 5 consecutive numbers in an array

OP here.

Q:

I want to find blocks of values of ascending order within a vector. e.g.:

[... 10 1 2 3 4 5 56 ...]

and [1 2 3 4 5] should be recognized.

it should also recognise e.g.:

[... 100 50 51 52 53 54 20 ...]


A:

% if not care about precisely 5 number block;
strfind(diff(x), [1 1 1 1])

% if has to be 5 consecutive number;
strfind(diff(x) == 1,[0 1 1 1 1 0])+1