How to modify and improve this for-loop that I wrote?

1 view (last 30 days)
Hey all,
I have a cell that includes some tables. In each table, I have the rrr24 column and PRECIP column. I want to calculate the correlation coefficient and RMSE for these columns for all tables that stored in the cell and save the results in a table. I want to have station_name of each table in the first column, correlation coefficient in second, and RMSE in the third column. I wrote this code so far:
for i=1:numel(newcell) %newcell is the name of my cell
A = newcell{1,i}.rrr24; %get rrr24 column
B = newcell{1,i}.PRECIP; %get PRECIP column
RMSE = sqrt(mean((A-B).^2)); %calculating RMSE
CC = corr(A,B); %calculating corelation coefficient
station_name = newcell{1,i}.station_name(1); %get station name in order to use in the table below
end
T = table(station_name, RMSE, CC); % save everything in a table in order to print later
But when I run this code I only see the last calculation in T. Also I would like to know how to make this for loop optimized and make it like a professional code.
Thank you all in advance

Accepted Answer

David Hill
David Hill on 15 Feb 2020
RMSE=arrayfun(@(x)sqrt(mean((newcell{x}.rrr24(:)-newcell{x}.PRECIP(:)).^2)),1:numel(newcell))';
CC=arrayfun(@(x)corr(newcell{x}.rrr24(:),newcell{x}.PRECIP(:)),1:numel(newcell))';
station_name=arrayfun(@(x)newcell{x}.station_name,1:numel(newcell))';
T=table(station_name,RMSE,CC);
  5 Comments
David Hill
David Hill on 15 Feb 2020
Did did not realize that you repeated the station_name for each data point. Need station_name(1). The below works for me with your data.
station_name=arrayfun(@(x)string(newcell{x}.station_name(1)),1:numel(newcell))';

Sign in to comment.

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!