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

13 views (last 30 days)
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;
% do nothing

Answers (1)

Voss on 15 Sep 2022
Edited: Voss on 15 Sep 2022
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], ...
% 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:
{'Failed'} {0×0 char} {'Poor'}
I modified your variables because (at least in what's shown) there are no matches.


Find more on Structures in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by