Applying a function row by row in a matrix
13 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!