How to Put an Arrays Elements in a Structure?

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

 Accepted Answer

Stephen23
Stephen23 on 11 Mar 2017
Edited: Stephen23 on 11 Mar 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 Comments

Thank you so much, Stephen!
What is this "1+" in code above?
Stephen23
Stephen23 on 11 Mar 2017
Edited: Stephen23 on 11 Mar 2017
I used the values of A as indices to get the required values from cell array C. As you know MATLAB indexing starts at one, but the values in A start from zero. So I add one to get indices starting from one.
Why does the values in A start from zero?
Could you please explain it a bit more or is there any link that I can refer to?
@Rightia Rollmann: You defined A in your question, on the very first line of code, like this:
A = [1; 1; 0; 0; 0; 0; 1];
I am sorry, but I do not know why you defined A like that. Perhaps you know why you defined A like that in your own question ?
But, given that you defined the values of A like that, that is what I had to work with. And because I wanted to use the values of A as indices into C, I had to add one to make the lowest index one, as required by MATLAB.
Indexing is very basic MATLAB concept, its usage is important for you to know how to use MATLAB:
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'
I asked it as separate question here!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!