assigning a a structured 2x2 matrix using a loop

1 vue (au cours des 30 derniers jours)
rony
rony le 13 Avr 2013
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.

Réponses (2)

ChristianW
ChristianW le 13 Avr 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 le 13 Avr 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

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by