Borrar filtros
Borrar filtros

Replace a field with another one in structure arrays

5 visualizaciones (últimos 30 días)
Tomer
Tomer el 15 de Mayo de 2024
Editada: Tomer el 15 de Mayo de 2024
Hi. I have two structure arrays (Data_1 and Data_2) of same size and field names (Camera1, Camera2, Camera3). I want to replace the contents of Camera1 in Data_1 with the contents of Camera1 in Data_2. The field Camera1 in Data1 is empty. I have used the following lines and when I run the code, the error is Unrecognized function or variable 'Data_2'. I am unable to fix this. I really appreciate some help or insights into this.
% Load the MAT files
load('Data_1');
load('Data_2');
% Check if both structure arrays have the 'Camera1' field
if isfield(Data_1, 'Camera1') && isfield(Data_2, 'Camera1')
% Replace the 'Camera1' field in Data_1 with the one from Data_2
Data_1.Camera1 = Data_2.Camera1;
% Save the modified structure array with the same name or a new name
save('Data_1_modified.mat', 'Data_1');
disp('Field replaced successfully.');
else
disp('One or both of the structure arrays do not contain the field "Camera1".');
end

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 15 de Mayo de 2024
Your structure name is apparently not Data_2. Check your workspace for the correct name.
Data_1.Camera1 = [];
Data_2.Camera1 = 5;
Data_1.Camera1 = Data_2.Camera1
Data_1 = struct with fields:
Camera1: 5
% your error - variable name is different
isfield(Data2, 'Camera1')
Unrecognized function or variable 'Data2'.
  2 comentarios
Tomer
Tomer el 15 de Mayo de 2024
Editada: Tomer el 15 de Mayo de 2024
Hi, many thanks. Indeed the data structures were result from ruinning a same program which gave an output structure: data_result. This was renamed as Data_1 and data_2. Perhaps, this was the reason behind this error.
filename = 'Data_2.mat';
save(fullfile(output_path,filename),'data_result');
What should be done while saving the files to avoid this kind of errors?
Cris LaPierre
Cris LaPierre el 15 de Mayo de 2024
Editada: Cris LaPierre el 15 de Mayo de 2024
Loading a mat file loads the variables that are saved in it to the workspace. It does not rename them. In the code you have shared, Data_2.mat conatins the variable data_result. Loading Data_2.mat will load data_result into the workspace. You must therefore give your variables the names you want them to have before saving them to a mat file.
To ensure the variables in your mat file do nore replace variables in your workspace (e.g. they have the same name), use the syntax S = load(___)
The variables are loaded into a structure and are accessed using dot notation (e.g. S.data_result). This way, they don't accidentally overwrite existing variables.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Labyrinth problems en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by