How to create a For Loop to Loop through all the rows in the matrix

Illustration
ishitaisha6840 - 2021-01-09T09:56:05+00:00
Question: How to create a For Loop to Loop through all the rows in the matrix

Hello all. I am working with time series data. I have a  matrix 142x240000 (142 rows, each row has 240000 columns). I want to calculate the the normalisation weight for each row. Below is the code:     %Normilisation time window width.half of the max period of the bandpass which is applied to the data prior to cross-correlation. (7Hz-40Hz) N=0.07; %Calculate the size of the signal to get number of columns and rows. n is number of rows and p is number of columns [n,p] = size(signal); %Calculate the normalised weights count = 0 for j = 1:142 %Matrix indexing, each row representing 10 minutes count = count + 1; ten = 240000; %Number of columns %Divide signal into 142 rows and 240000 columns A(count,:) = signal(((j-1)*ten)+1:ten*j); The above code runs just fine. It takes the signal that I have and divides it into 142 rows and 240000 columns. I now need to calculate the normalisation weight for each row. In the end, I want to have a matrix called weight with the size 142x1, each row should have the calculated weight of it's corresponding row from matrix A. The formula for calculating weight is:   weight =(1/((2*N)+1))*sum(abs(row)). The code I have to calculate the weight is:     for i = 1:142 weight(i)=(1/((2*N)+1))*sum(abs(A)); %The A here should be the rows(row1,row2,...till row 142) end How do I make the For Loop to calculate the weight from row 1 to row 142 and store the calculated weights as a 142x1 matrix  

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

You don't need any loops at all...use the  MATrix LABoratory vectorized operations. You already have the the  signal in the array, you don't need anything to use it--

 

weight=1/(2*N+1)*sum(abs(signal),2);
The only "trick" here is to use the optional second argument to sum to add row elements (2nd dimension) instead of the default by column.
NB: The above assumes your parentheses-nesting is correct as the formula is written that the weight is intended as
wt = SUM(|signal|)/(2N+1)

and not as

wt = 1/{(2N+1)*SUM(|signal|)}

If it is instead the latter, you'll need

weight=1./((2*N+1)*sum(abs(signal),2));

using the "dot" divide operator for element-wise division.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!