If I have a short list (let’s say two or three elements) I would like to have function that split it in several variables. Something like that:
li=[42 43];
[a b]=split(li)
--> a=42
--> b=43
I am looking for some way to make my code shorter in matlab. This one would be nice in some situations For instance:
positions=zeros(10,3);
positions= [....];
[x y z]=split(max(positions,1))
instead of doing:
pos=max(positions,1)
x=pos(1);
y=pos(2);
z=pos(3);
The only way I know of to do this is to use
deal. However this works with cell arrays only, or explicit arguments in todeal. So if you want to deal matrices/vectors, you have to convert to a cell array first withnum2cell/mat2cell. E.g.:The first form is nice (
deal(x,y,...)) since it doesn’t require you to explicitly make the cell array.Otherwise I reckon it’s not worth using
dealwhen you have to convert your matrices to cell arrays only to convert them back again: just save the overhead. In any case, it still takes 3 lines: first to define the matrix (e.g.li), then to convert to cell (lic), then to do thedeal(deal(lic{:})).If you really wanted to reduce the number of lines there’s a solution in this question where you just make your own function to do it, repeated here, and modified such that you can define an axis to split over:
Then use like this:
It still does the matrix -> cell -> matrix thing though. If your vectors are small and you don’t do it within a loop a million times you should be fine though.