brucezepplin
brucezepplin

Reputation: 9752

Populate vectors using for loop

I have a solution to creating a vector for just one element of a matrix:

[dx,dy] = gradient(Im);
orient11 = [(-dx(1,1)) (dy(1,1)) 0];

where

size(orient11) =

0 0 0

ie for the first element of orient, namely orient11, is a vector. How do I do this for all the other elements, so I have orient12, orient13....orientnn. I know I need a for loop, however what object do I store the vectors into from the for loop? I have discovered I can't create a matrix of vectors.

Thanks in advance.

Upvotes: 0

Views: 354

Answers (2)

Eitan T
Eitan T

Reputation: 32920

You can try building an N-by-N-by-3 matrix, but it won't be so convenient to manipulate. This is because extracting a vector from this matrix would yield a 1-by-1-by-3 vector, which you would need to reshape. Definitely not fun.

Instead, I suggest that you build an N-by-N cell array of 1-by-3 vectors, like so:

[dx, dy] = gradient(Im);
vec = @(i)[-dx(i), dy(i), 0];
orient = arrayfun(vec, reshape(1:numel(dx), size(dx)), 'UniformOutput', 0);

To access a vector, use the curly braces. For example, the vector at the (1, 2) position would be:

orient12 = orient{1, 2};

Hope it helps!

Upvotes: 1

Ben A.
Ben A.

Reputation: 1039

v = -2:0.2:2;
[x,y] = meshgrid(v);
z = x .* exp(-x.^2 - y.^2);
[px,py] = gradient(z,.2,.2);

orient11 = [(-px(1,1)) (py(1,1)) 0]; % based off of your concatination there.
size(orient11)

I then get:

ans =

     1     3

If you're looking to just grab the first column of data from the gradients you have and want to just stack zeros with them, you can do this:

orient11 = [(-px(:,1)) (py(:,1)) zeros(size(px,1),1)];

Instead of a for loop.

Update:

Orient = zeros(size(px,1),3,size(px,2));
for n = 1:size(px,1)
    Orient(:,:,n) = [(-px(:,n)) (py(:,n)) zeros(size(px,1),1)];
end

The layout of Orient is now your -px, py, 0 in layers. Each layer represents the column from the initial data. So if you wanted to get access to row 4 column 14, you would call Orient(4,:,14).

Hope that makes sense and helps!

Upvotes: 1

Related Questions