How to Put an Arrays Elements in a Structure?

2 visualizaciones (últimos 30 días)
Rightia Rollmann
Rightia Rollmann el 11 de Mzo. de 2017
Editada: Stephen23 el 12 de Mzo. de 2017
Is there any way to get as same a result as the code below without having that annoying for loop?
A = [1; 1; 0; 0; 0; 0; 1];
for i = 1 : 7
if A(i) == 0
B(i).C = 'w';
elseif A(i) == 1
B(i).C = 'b';
end;
end

Respuesta aceptada

Stephen23
Stephen23 el 11 de Mzo. de 2017
Editada: Stephen23 el 11 de Mzo. de 2017
Here are three ways:
A = [1; 1; 0; 0; 0; 0; 1];
C = {'w','b'};
B = struct('C1',C(1+A)); % if the structure does not exist.
[B.C2] = deal(C{1+A}); % if the structure already exists.
[B.C3] = C{1+A}; % if the structure already exists (not all versions).
Giving:
>> B.C1
ans =
b
ans =
b
ans =
w
ans =
w
ans =
w
ans =
w
ans =
b
>> B.C2
ans =
b
ans =
b
ans =
w
ans =
w
ans =
w
ans =
w
ans =
b
  6 comentarios
Rightia Rollmann
Rightia Rollmann el 11 de Mzo. de 2017
Editada: Rightia Rollmann el 11 de Mzo. de 2017
My question is about your code.
B = struct('C1',C(1+A)); % if the structure does not exist.
it beautifully works and I just want to know about how it works step-by-step. I don't fully understand how it calculates the values; especially the part below:
C(1+A)
ans =
'b' 'b' 'w' 'w' 'w' 'w' 'b'
Rightia Rollmann
Rightia Rollmann el 11 de Mzo. de 2017
Editada: Rightia Rollmann el 11 de Mzo. de 2017
I asked it as separate question here!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by