How to save struct data in for loop

Hi,
I am working in a for loop where for each iteration I get a new structure data with 3 fields in all of them. How do I store all of these data points so that I could use them together? I tried working with the following format but I am getting the error "Subscripted assignment between dissimilar structures."
The m.get_data() returns a struct of three fields each containg 1024 values.
for i=1:10
data_struct(i)=m.get_data();
end

5 comentarios

Walter Roberson
Walter Roberson el 23 de Oct. de 2020
Editada: Walter Roberson el 23 de Oct. de 2020
You have a left-over value for data_struct in your workspace. Clear it, or better yet use a different variable name.
Suman Chatterjee
Suman Chatterjee el 23 de Oct. de 2020
Walter Roberson could you please explain what is the meaning of the error "Subscripted assignment between dissimilar structures" .And how to avoid it.
Walter Roberson
Walter Roberson el 23 de Oct. de 2020
Also note that in order to assign an entire struct into an existing struct array, the structure fields must be in exactly the same order between the two.
Suman Chatterjee
Suman Chatterjee el 23 de Oct. de 2020
Can i save them in any other way. My objective is to save the individual struct for eact loop.
Walter Roberson
Walter Roberson el 23 de Oct. de 2020
Use dynamic structure names so your data_struct is a struct with multiple field names. Then use save() with the -struct option; that will create one variable name in the .mat file for each field name in the struct.

Iniciar sesión para comentar.

 Respuesta aceptada

Nitin Kapgate
Nitin Kapgate el 28 de Oct. de 2020
You can overcome the problem by pre-allocating the array of structures as follows:
clear all; % Clear the workspace
N = 10;
% Pre-allocate the array of structures
structArray1(N) = struct('field1',[], 'field2',[], 'field3',[]);
for i=1:N
field1 = "field1";
field2 = "field2";
field3 = "field3";
structArray1(i)=getStruct(field1, field2,field3);
end
Alternatively, instead of pre-allocating before the loop, you can also loop backwards so that all the memory allocation is done in the first iteration itself.
N = 10;
for i=N:-1:1
field1 = "field1";
field2 = "field2";
field3 = "field3";
structArray2(i)=getStruct(field1, field2,field3);
end
structArray2 = fliplr(structArray2); % Get back the array of structures in correct order
The getStruct function is as follows:
function outStruct = getStruct(field1, field2,field3)
% returns a struct with 3 fields
outStruct.field1 = field1;
outStruct.field2 = field2;
outStruct.field3 = field3;
end

Más respuestas (0)

Categorías

Productos

Versión

R2020b

Preguntada:

el 23 de Oct. de 2020

Respondida:

el 28 de Oct. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by