Applying a function row by row in a matrix

18 visualizzazioni (ultimi 30 giorni)
I want to apply a function to each row in a matrix. For example, my function is function(R,L); where R is the input (row) and L is the difference between the max and min value of that R (row). How can I do this program?
I tried this way
MyData=load('file.dat'); %this is a 100x100 matrix
NewMat=zeros(100,100); %create a zero matrix
For i=1:100
j=MyData(i,:);
L=max(j)-min(j);
NewData=function(j,L);
end
Now I don't know how to replace the NewData for each 'i' value in the NewMat. My logic here is to create a zero matrix, then apply the function to each row in the original data(NewData), then replace the corresponding row in the zero matrix with the NewData.
Please help me to make this program

Risposta accettata

Guillaume
Guillaume il 6 Nov 2014
You've already written most of the code needed, the only thing left to do is to put NewData in the corresponding row of NewMat, so it's simply:
NewMat(i, :0 = NewData;
within the loop. Note that this will fail if your function returns something that has more or less than 100 elements, since you've defined 100 columns for NewMat.
I would also advise you to use better names for your variables i, j and L. Something that makes it obvious what they are for. Also note that for is lowercase. So:
MyData=load('file.dat'); %this is a 100x100 matrix
NewMat=zeros(100,100); %create a zero matrix
for row = 1:100
rowdata = MyData(row, :);
rowrange = max(rowdata) - min(rowdata);
NewMat(row, :) = fn_with_a_better_name(rowdata, rowrange);
end
Note that since you're passing rowdata to your function, it could calculate the rowrange itself.

Più risposte (0)

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by