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

2 views (last 30 days)
Behzad Navidi on 15 Feb 2020
Commented: Behzad Navidi on 15 Feb 2020
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.

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);

Behzad Navidi on 15 Feb 2020
Thanks again. This code gave the same error too. I attaching my cell here. I don't know what is the cause of this problem.
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))';
Behzad Navidi on 15 Feb 2020
Thank you so much ?