assigning a a structured 2x2 matrix using a loop

2 次查看(过去 30 天)
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.

回答(2 个)

ChristianW
ChristianW 2013-4-13
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 2013-4-13
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by