Replace a field with another one in structure arrays
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Cris LaPierre
2024-5-15
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 个评论
Cris LaPierre
2024-5-15
编辑:Cris LaPierre
2024-5-15
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!