필터 지우기
필터 지우기

Replace a field with another one in structure arrays

조회 수: 5 (최근 30일)
Tomer
Tomer 2024년 5월 15일
편집: Tomer 2024년 5월 15일
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

채택된 답변

Cris LaPierre
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
Data_1 = struct with fields:
Camera1: 5
% your error - variable name is different
isfield(Data2, 'Camera1')
Unrecognized function or variable 'Data2'.
  댓글 수: 2
Tomer
Tomer 2024년 5월 15일
편집: Tomer 2024년 5월 15일
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 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 CenterFile Exchange에서 Labyrinth problems에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by