Replace a field with another one in structure arrays
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Cris LaPierre
am 15 Mai 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
% your error - variable name is different
isfield(Data2, 'Camera1')
2 Kommentare
Cris LaPierre
am 15 Mai 2024
Bearbeitet: Cris LaPierre
am 15 Mai 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Import and Analysis finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!