I have just been bitten by some careless coding, but I am surprised that MATLAB lets me do it and that mlint didn't provide a warning. Why does MATLAB let you do this:
x = {1,2};
y = x{:};
what I wanted to do (and I am sure there are a number of other ways of doing it) was
y = [x{:}];
I can see the advantage of cell array expansion for referencing and parameter passing. For example,
z = magic(5);
z(x{:})
xy = {1:10, 0:9};
plot(xy{:});
Is there any reason for
y = x{:};
to be valid. I feel like it should return an error about the RHS returning more arguments than the LHS.

 Akzeptierte Antwort

Jan
Jan am 21 Jul. 2011

1 Stimme

This is the standard behaviour of Matlab:
x = {1, 2};
y = x{:}; % y is x{1}
You see the same method for:
a = rand(1, 10);
b = max(a);
Why is this equivalent? Because MAX replies 2 outputs as "x{:}" and if just the 1st is caught, the 2nd is ignored. Therefore these methods are equivalent also:
x = {1, 2};
[y1, y2] = x{:}
a = rand(1, 10);
[b1, b2] = max(a)
So I would not expect an MLint-warning for a standard behaviour.

1 Kommentar

Daniel Shub
Daniel Shub am 6 Aug. 2011
I think you explanation is the best, even if I don't fully agree. I see a difference if you consider max(a) and x{:} without semicolons (max returns one answer and x returns two).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Sean de Wolski
Sean de Wolski am 21 Jul. 2011

1 Stimme

One reason: For a function that takes varargin you can feed it all contents of a cell as a separate input.
x = {1,2,3,4}
cat(3,x{:})
Yes, it frustrates me some times too!

3 Kommentare

Daniel Shub
Daniel Shub am 21 Jul. 2011
Yes, I agree and this is basically what I pointed out in my plot(xy{:}) example. What I want to know is if y = x{:} is useful. If the only reason it is valid is so that f(x{:}) can work then I think mlint should provide a warning (and even better MATLAB should throw an error).
Sean de Wolski
Sean de Wolski am 21 Jul. 2011
I disagree; that functionality is quite useful. What if the cell contains different sized elements? Concatenating them as you have done will fail.
Daniel Shub
Daniel Shub am 21 Jul. 2011
I don't understand. Yes, x = {1, [1, 2]}; y = [x{:}]; will fail and y = x{:} won't fail, but why would you want y = x{:}?

Melden Sie sich an, um zu kommentieren.

Fangjun Jiang
Fangjun Jiang am 21 Jul. 2011

1 Stimme

Maybe one way to explain it is to treat it as the variable output argument. Like,
MaxValue=max(1:10);
[MaxValue,Index]=max(1:10);
You can do:
x={1,2};
y=x{:}
[a b]=x{:}

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by