How to assign several values at once to a field in structure
12 views (last 30 days)
Show older comments
I have a matrix P1
P1= [2 42 25
6 37 57
3 55 16]
and a structure A (containing 6 elements) with several fields among them there is a field called x
A.x
I want to have
A(i).x=P1(ind,2)
where
ind =P1(i,1)
For example
A(3).x=55 and A(6).x=37
What I did is
v=P1(:,1)
[A(v).x] = P1(:,2);
But I am getting this error
Indexing cannot yield multiple results.
How to fix it?
0 Comments
Accepted Answer
Stephen23
on 19 Mar 2016
Edited: Stephen23
on 19 Mar 2016
>> P1= [2 42 25
6 37 57
3 55 16];
>> C = num2cell(P1(:,2));
>> A = struct('x',cell(1,6));
>> I = P1(:,1);
>> [A(I).x] = deal(C{:}); % or = C{:};
>> A.x
ans =
[]
ans =
42
ans =
55
ans =
[]
ans =
[]
ans =
37
3 Comments
Stephen23
on 19 Mar 2016
Edited: Stephen23
on 19 Mar 2016
You need to learn what comma-separated lists are. The RHS and LHS are not one variable each, but they actually consist of multiple separate variables and allocations. Therefore an operation like + cannot be performed on them, because it is equivalent to this:
a,b,c = a,b,c + X,Y,Z
which makes no sense (in MATLAB anyway).
I would suggest that you simplify your data by using one simple numeric array, and then all of these operations become trivial. Beginners often put their data in the most complicated nested structures and cell arrays, and are then surprised when it is challenging to work on the data. Put the data in a simple numeric array and you won't have these problems at all.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!