assigning a a structured 2x2 matrix using a loop

조회 수: 1 (최근 30일)
rony
rony 2013년 4월 13일
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에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by