MATLAB: Assign matrix to struct

matrixstruct

Hi everyone
Can you help me for my code?.
I want to assign matrix b to struct g.a at position c.
g(1).a=[1 2 3 4]'
g(2).a=[1 1 3 4]'
g(3).a=[4 3 1 2]'
c=[1 2]
b=[ 3 3 3 3;4 5 4 4]'
My hope output is g.a =
3 4 4
3 5 3
3 4 1
3 4 2
Thank you so much.

Best Answer

As per jan's comment, g.a means nothing. If you type g.a in the command window, you will get 3 outputs (3 times: ans = ...).
[g.a] will indeed return a matrix, which is the horizontal concatenation of all the outputs of g.a. However, [g.a] does not exist in the structure. I believe that you've misunderstood how structures work if that's what you want.
If you want to replace g(c(i)).a by b(:, i), then the easiest is a loop:
for col = 1:numel(c)
g(c(col)).a = b(:, col);
end
While it can be done without a loop, it's awkward and probably slower:
a = {g.a}; %concatenate all in a cell array
a(c) = num2cell(b, 1); %replace columns determined by c by columns in b
[g.a] = a{:}; %put back into structure