assigning a a structured 2x2 matrix using a loop
5 views (last 30 days)
Show older comments
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.
0 Comments
Answers (2)
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
0 Comments
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
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!