Applying a function row by row in a matrix

조회 수: 11 (최근 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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by