Creating a structure and fields in nested loops
Show older comments
I'm extracting information from a large Exel sheet, it has headers 'category, 'item', 'variety', 'date', 'price', 'unit'; the 'item' header contains fruits and vegetables, and 'variety' contains the different varieties, and 'item' and 'variety' columns are the only 2 concerned in this task.
I'm trying to create a structure with field names 'apples', 'pears', 'carrots, 'cabbage' and for each field it contains an array of distinct varieties of the corresponding item, so it looks something like:
structure=
apples: [distinct varieties for apples]
pears: [distinct varieties for pears] ...
Here's my attempt:
data=readtable('fruitvegprices.csv');
m=1;%m,n,p are counters
n=1;
p=1;
items={'apples','pears','carrots','cabbage'};
matrix=cell(length(items),1);%creates 4-row matrix, where each row
%contains distinct varies of each corresponding item
[A, ia, ic]=unique(data.variety,'stable');
for i=1:length(data.item)
if ismember(data.item{i},items)%checks if it's the item we want
for j=1:length(ia)
if strcmp(data.item{ia(j)},data.item{i})==0 %checks if variety correponds to the correct item
continue
end
matrix{find(strcmp(data.item{i},items)),p}=data.variety{ia(j)};
p=p+1;
end
lst(1).(data.item{i})=matrix{find(strcmp(data.item{i},items)),:};
end
end
My approch was to first obtain a list 'A' of distinct varies for all items, then loop through 'ia' to identity any duplicated varieties for each of the 4 items. If succesful I would obtain a 4-row matrix whose rows are the distinct varieties for the 4 items, then I could assign the corresponding row and structure field.
However, this did not quite work out the way I planned, I think it's giving me a matrix of ALL varities, and the output for the structure is not as anticipated too:

Could someone enlighten me?
Thank you very much!
4 Comments
Image Analyst
on 12 Dec 2021
You forgot to attach 'fruitvegprices.csv'. I don't expect answers until you attach it.
Achuan Chen
on 12 Dec 2021
Stephen23
on 12 Dec 2021
Is there a particular reason you need to use a structure? The data are very neatly organized into columns, so using a table would most likely be much easier for you when processing that data.
Achuan Chen
on 12 Dec 2021
Accepted Answer
More Answers (0)
Categories
Find more on Data Import from MATLAB 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!