How to assign several values at once to a field in structure
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
etudiant_is
el 19 de Mzo. de 2016
Comentada: etudiant_is
el 19 de Mzo. de 2016
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 comentarios
Respuesta aceptada
Stephen23
el 19 de Mzo. de 2016
Editada: Stephen23
el 19 de Mzo. de 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 comentarios
Stephen23
el 19 de Mzo. de 2016
Editada: Stephen23
el 19 de Mzo. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!