Create column into struct if 'if statement' met a condition

조회 수: 6 (최근 30일)
Stefano Alberti
Stefano Alberti 2022년 9월 13일
댓글: Voss 2024년 3월 27일 18:38
Hi all,
I have a structure and data stored into a table, I'd like to compare data into defined column inside the structure and a column of table, if one of the values inside column of the table is equal to value inside column of strucuture I'd like add a value contained into another (and new) column inside the structure.
To be more precis, so if one of the values contained into 'stored_PCI.SU{:,1}' is equal to value contained into shape_area(i).SU_name, I'd like to add a new column into shape_area with the corresponding value of 'PCI' from table.
I thought about a for cycle, or a cellfun (honestly I never used this function).
I've tried this, but it ain't working.
for i = 1: height(shape_area)
if ismember(stored_PCI{:,1},shape_area(i).SU_name)
% add column;
else
% do nothing
end
end
Thanks!

답변 (1개)

Voss
Voss 2022년 9월 15일
편집: Voss 2022년 9월 15일
Here's one way:
% construct a modified version of your variables:
shape_area = [ ...
struct('Geometry','Polygon','Column1','Very Good','Column2',5,'SU_name','115_02'); ...
struct('Geometry','Polygon','Column1','Fair','Column2',3,'SU_name','booey'); ...
struct('Geometry','Polygon','Column1','Not too shabby','Column2',1,'SU_name','114_01'); ...
];
stored_PCI = table( ...
{'110_7';'114_01';'115_02';'Foxtrot_3';'Whiskey_36'}, ...
{'Fair';'Poor';'Failed';'Fair';'Good'}, ...
[55;40;10;55;70], ...
'VariableNames',{'SU','PCI','PCI_numb'});
% initialize PCI field in shape_area struct array with empty character
% arrays:
[shape_area.PCI] = deal('');
% find which shape_area.SU_name match stored_PCI.SU (ism)
% and where in stored_PCI.SU they match (idx)
[ism,idx] = ismember({shape_area.SU_name},stored_PCI.SU);
% set shape_area.PCI to stored_PCI.PCI for those:
[shape_area(ism).PCI] = stored_PCI.PCI{idx(ism)};
% now there are PCI in shape_area:
disp({shape_area.PCI});
{'Failed'} {0×0 char} {'Poor'}
I modified your variables because (at least in what's shown) there are no matches.

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by