How to assign several values at once to a field in structure

15 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Stephen23
Stephen23 il 19 Mar 2016
Modificato: Stephen23 il 19 Mar 2016
You need to use deal or its newer alternative syntax:
>> 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 Commenti
Stephen23
Stephen23 il 19 Mar 2016
Modificato: Stephen23 il 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.
etudiant_is
etudiant_is il 19 Mar 2016
In reality, I have like 15 specific fields for each element I am processing. So I thought putting everything in a structure for each element, then modifying them at need is the best approach. The code is working but with a lot of nested for loops and hence it takes a long time. So I was trying to optimize and get rid of these for. And hence the problem I was asking about. But it seems I can not do it like this. Anyway, thanks a lot for your advice and answer.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by