1
votes

I wish to populate an nxn matrix with vectors. I have the following:

[x y] = meshgrid(a);
for i:size(a,1)
    for j:size(a,2)
        b = [x(i,j),y(i,j) 0];
    end
end

I think may be being a bit naive here as I am expecting a range of different numbers within the vector elements of b. Instead I am getting the elements of b are all equal. also

size(b) = 1 3
size(b(1,1)) = 1 1

I am expecting size(b(1,1)) = 1 3 as each element in b should be a vector of length 3. can someone tell me where I have gone wrong? Thanks very much.

2
b{i,j} = [x(i,j),y(i,j) 0]; ?Junuxx
hi Junuxx - when I try this I get ??? Cell contents assignment to a non-cell array object.brucezepplin

2 Answers

3
votes

You are overriding the value of b in the loop. Try:

[x y] = meshgrid(a);
b = zeros( size(a,1) size(a,2) 3);
for i:size(a,1)
    for j:size(a,2)
        b(i,j,:) = [x(i,j),y(i,j) 0];
    end
end
2
votes

There are a few ways how you could fill an n-by-n array b with vectors:

(1) You can create a n-by-n-by-3 array, so that squeeze(b(i,j,:)) returns the vector i,j as a 3-by-1 array:

a=1:3,
[x y] = meshgrid(a);
b = cat(3,x,y,zeros(size(x));

(2) You can create an n-by-n cell array so that b{i,j} returns the vector i,j

a=1:3,
[x y] = meshgrid(a);
b = arrayfun(@(x,y)[x,y],x,y,'uni',false);