How Do I use nested for loops to first go through every column, and then do a calculation for every row of that column.

28 views (last 30 days)
I have a data set that is about 10,000 rows and 51 columns. I’m trying to create nested for loops where it will go through every row of the current column, do a calculation, and then move to the next column and replace all the original values with the new ones. This might be simple but I’m still a beginner to coding but I just can’t get this to work right.
  8 Comments
David Fletcher
David Fletcher on 6 Apr 2018
That's one hell of a calculation you've got in the for loop - you must have got RSI just typing it out. Have a look at the answer I've put below and see if it works OK (and you understand everything that is happening)
Brendan Hamm
Brendan Hamm on 6 Apr 2018
A couple of quick points:
1) Without using functions, you do have the right approach at a nested loop.
2) for the rows loop, you can actually go all the way to rows-8, that is (9:1:rows-8)
3) You may not want to start at column = 1, but rather column = (2:1:ncolumns) as it appears that column 1 is the xdata.
4) Do you also want to average the data in rows 1 through 8, etc. but using less data points? if so, consider padding with zeros to perform the calculations.
5) Is there any point of confusion you had? It seems you are doing what you set out to. Presuming the code you wrote is doing what you want.

Sign in to comment.

Answers (1)

David Fletcher
David Fletcher on 6 Apr 2018
matrix = csvread('M3_Data_HeatingTimeHistories2.csv')
[rows,ncolumns] = size(matrix); % finds size of matrix
xdata = matrix(:,1);
ydata = matrix(:,2:end);
window=8
for column = (1:(ncolumns-1))
for row = (window+1:rows-window)
ydata(row,column)=sum(ydata(row-window:row+window,column))/(2*window+1)
end
end

Categories

Find more on Loops and Conditional Statements 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!