Sorry for the beginners matlab question…
function [ A B C ] = crunch(i)
A = i^2;
B = 2*A;
C = A+B;
end;
vals = zeros(5,3);
for i=1:5
vals(i,:) = crunch(i);
endfor;
disp(vals);
This is not the result I expected.
vals =
1 1 1
4 4 4
9 9 9
..... etc
if I instead explicitiy place A, B & C in a row vector and return that, then everything is fine.
function retval = crunch(i)
A = i^2;
B = 2*A;
C = A+B;
retval = [ A B C ];
end;
ans =
1 2 3
4 8 12
9 18 27
16 32 48
25 50 75
What’s going wrong here?
MATLAB is generally reluctant to give you multiple return values unless you explicitly ask for them. So in the first version, when you do:
What MATLAB does is take just the first return value from
crunch(i), then broadcast that to all the elements ofvals(i,:). It’s like doing:If you explicitly ask MATLAB for multiple return values, you get the desired behavior. As @igon notes, this version will fix the behavior:
Or, I think if
valswere a cell array,vals{i, :} = crunch(i);would work too, but that doesn’t make sense in this case — using a regular (not cell) array seems like the right approach in your code.