MATLAB Answers

# Please help me to correct my for-loop

2 views (last 30 days)
Behzad Navidi on 30 Mar 2020
Commented: Behzad Navidi on 31 Mar 2020
Hey all, I have a 1x3 cell with three 360x3 table. Each table has a column date with 30 years of the monthly data (30x12 = 360).
So I used this code below:
%get first array of the cell
table = CELL{1};
table.month = month(tbl.dates);
table.seasons = floor(tbl.month ./ 3);
table.seasons(tbl.seasons == 4) = 0;
table.seasons = categorical(tbl.seasons, [0 1 2 3], ["Spring", "Summmer", "Autumn", "Winter"]);
[group, mean_table] = findgroups(table(:, 'seasons'));
mean_table.rrr24 = splitapply(@sum, table.rrr24, group);
This code above calculates seasonal data just for the first array of the cell:
meanTbl =
4×2 table
season rrr24
______ ______
Spr 14.038
Sum 35.004
Aut 10.949
Win 16.958
Now I want to apply the above-mentioned code to all arrays of cell; then save the result in another cell (3 x 4, Three years and four seasons).
Here is my try I want to ask you if you please correct me:
for i = 1:numel(CELL)
table.month(i) = month(table(i).dates);
table(i).seasons = floor(table(i).month ./3);
table(i).seasons(table(i).seasons ==4) = 0;
table(i).seasons = categorical(table(i).seasons, [0 1 2 3], ["Spring", "Summer", "Autumn", "Winter"]);
[group, mean_table(i)] = findgroups(table(i)(:, 'seasons'));
mean_table(i).rrr24 = splitapply(@sum, table(i).rrr24, group);
for j = 1:3
newCELL{j,i} = mean_table(i); %newCELL is 3 x 4 cell array
end
end
Thank you so much.

#### 0 Comments

Sign in to comment.

### Accepted Answer

Geoff Hayes on 31 Mar 2020
Behzad - I don't really understand why in your code you have variables named table and then tbl. Perhaps both are the same variable and so there has been a typo in your code. I do recommend against using variable names that are identical to built-in MATLAB function (see table). If you want to loop over each set of 30 year data in your cell array then you could try something like
load ExampleCell.mat;
meanTableDataArray = cell(length(CELL),4);
for j = 1:length(CELL)
sampleTableData = CELL{j};
sampleTableData.month = month(sampleTableData.dates);
sampleTableData.seasons = floor(sampleTableData.month ./3);
sampleTableData.seasons(sampleTableData.seasons ==4 ) = 0;
sampleTableData.seasons = categorical(sampleTableData.seasons, [0 1 2 3], ["Spring", "Summer", "Autumn", "Winter"]);
[group, mean_table] = findgroups(sampleTableData(:, 'seasons'));
mean_table.rrr24 = splitapply(@sum, sampleTableData.rrr24, group);
for k = 1:4
meanTableDataArray{j,k} = mean_table(k,:); % extracts as a table
end
end
I haven't tested the above but I think that it will give you an idea of what you can do. Note how it is more similar to the first block of code that you posted, and that the only indexing we use (with j) is when we extract the jth table data.

#### 1 Comment

Behzad Navidi on 31 Mar 2020
Thank you so much.

Sign in to comment.

R2018b