assigning a a structured 2x2 matrix using a loop

1 view (last 30 days)
I have written code like this:
detresp = struct ('a','b','c','d');
and later in the code comes a while loop where i have to use an array of detresp structures.
centroid is a precomputed M*2 matrix. I need to assign centroid to 'a' field of each cell of the detresp array.
the line: detresp(framecount).a=centroid;
throws an error saying that the left hand side is not a valid target for assignment. Any help is highly appreciated.
Thank you.

Answers (2)

ChristianW
ChristianW on 13 Apr 2013
M = 5;
centroid = rand(M,2);
detresp = struct('a',num2cell(centroid,2),'c','d');
or
detresp = struct('a',cell(M,1),'c','d');
for k = 1:M
detresp(k).a = centroid(k,:);
end

Image Analyst
Image Analyst on 13 Apr 2013
It's a bit tricky and unexpected. You need to preallocate all the members that you will ever need. See this example:
numberOfFrames = 5; % Whatever...
% Preallocate all the a, b, c, and d that we will ever need.
a = zeros(numberOfFrames, 2);
b = zeros(numberOfFrames, 1);
c = zeros(numberOfFrames, 1);
d = zeros(numberOfFrames, 1);
detresp = struct('a', 'b', 'c', 'd')
for k = 1 : numberOfFrames
detresp(k).a = rand(2,1)
detresp(k).b = rand(1,1)
detresp(k).c = rand(1,1)
detresp(k).d = rand(1,1)
end

Community Treasure Hunt

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

Start Hunting!