Indexing can't yield multiple results.

I am trying to save multiple values from a database as variables at once by indexing. I don't know why this isn't working but might have the wrong method, if this doesn't work how do I do this:
[x, y, z, vx, vy, vz] = EarthPosData(Start,:);
the database gives me the correct result since:
>> EarthPosData(Start,:)
ans =
1.0e+08 *
1.4810 -0.2964 -0.0002 0.0000 0.0000 -0.0000
So it seems that I just can't use this method? so then how do I get xyz... without having 6 lines of code?
thanks

 Accepted Answer

You can do something similar to that with a cell array or the deal function, but the right side of the assignment has to be a comma-separated list.
This works:
EarthPosData = randi(9, 3, 6); % Create Data
EarthPosDataCell = mat2cell(EarthPosData, size(EarthPosData,1), ones(1,size(EarthPosData,2)));
[x, y, z, vx, vy, vz] = EarthPosDataCell{:};
You’ll have to verify that it works with your data.

5 Comments

That seems really complex, there must be an easier way to do this right? I mean e.g. i can do [Row, col] = size (somematrix); Which gives me two results. Why can't i do that with indexing?
@Martin Brandel: because indexing into an array using parentheses () returns one array (which may be empty, scalar, or larger). Indexing using curly braces {} returns zero or more values (variables) in a comma separated list. MATLAB function also use comma separated lists for multiple input or output arguments.
This is why it is possible to do things like this:
>> C = {3,6};
>> max(C{:})
ans =
6
or similarly for output arguments:
>> [C{:}] = size(NaN(3,4))
C =
[3] [4]
But MATLAB does not allow one array to be assigned to multiple variables as you want to do. You have to make this assignment explicitly.
Learn to use the correct terminology: "Which gives me two results" is meaningless, because a "result" is not any kind of MATLAB data type, syntax, or variable. MATLAB has various arrays (indexing with parentheses returns one array) or comma separated lists (function inputs and outputs, or indexing cell arrays with curly braces).
@Stephen Cobeldick aah that explains it, thank you.
So then my question would be: is there any way to assign multiple variables from one array? or do I have to change it to a comma separated list and then do it my way like the answer above?
Stephen23
Stephen23 on 12 Sep 2016
Edited: Stephen23 on 12 Sep 2016
@Martin Brandel: you will have to use a comma separated list. Star Strider's answer gives a reasonable way of doing this. Generally though, it is more convenient to keep data together, rather than splitting it apart: unless there is a great need to define those variables, personally I would just keep them in one array and using indexing or fieldnames to access them.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!