Reputation: 39585
I am working on matlab with a matrix. I would like to reproduce this matrix and apply sum for elements in rows.
I have two vectors defined by this code:
unitsvector=1:5;
reordervector=1:3;
Then, I create an empty matrix to store the values:
resultvec=zeros(size(unitsvector,2)*size(reordervector,2),3);
Finally, here is the loop I use but it is not working:
for a=1:length(resultvec)
for b=reordervector
for c=unitsvector
resultvec(a,1)=b;
resultvec(a,2)=c;
resultvec(a,3)=b+c;
end
end
end
How could I reproduce this matrix in matlab. Thanks for your help.
Upvotes: 0
Views: 188
Reputation: 18177
Why are you looping at all? sum
actually has vector support; a simple resultvec = [a(:,1),a(:,2),sum(a,2)]
would work.
As to your code: of course it doesn't work. What do you expect to be the contents of a
? You create a
as a loop index, which runs over the range 1:length(resultvec)
. Ergo, within each loop iteration a
is a scalar. You try to call it like it is a three-element vector. Nor do you define b
and c
. This might be possible in R, judging where you're coming from, but not in MATLAB.
Upvotes: 1
Reputation: 1362
You can use meshgrid
for this without a for loop.
[a,b] = meshgrid(1:5,1:3);
M = [a(:) b(:)];
M(:,3) = sum(M,2); % Create third column by summing first two
Upvotes: 1