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!