Applying a function row by row in a matrix

13 ビュー (過去 30 日間)
aneps
aneps 2014 年 11 月 6 日
回答済み: Guillaume 2014 年 11 月 6 日
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

採用された回答

Guillaume
Guillaume 2014 年 11 月 6 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by