[英]Look at each row separately in a matrix (Matlab)
I have a matrix in Matlab(2012) with 3 columns and X number of rows, X is defined by the user, so varies each time. 我在Matlab(2012)中有一个矩阵,其中包含3列和X行数,X由用户定义,因此每次都不同。 For this example though I will use a fixed 5x3 matrix.
对于本示例,我将使用固定的5x3矩阵。
So I would like to perform an iterative function on each row within the matrix, while the value in the third column is below a certain value. 因此,我想在矩阵的每一行上执行迭代函数,而第三列中的值低于某个特定值。 Then store the new values within the same matrix, so overwrite the original values.
然后将新值存储在同一矩阵中,因此覆盖原始值。
The code below is a simplified version of the problem. 下面的代码是问题的简化版本。
M=[-2 -5 -3 -2 -4]; %Vector containing random values
Vf_X=M+1; %Defining the first column of the matrix
Vf_Y=M+2; %Defining the secound column of the matrix
Vf_Z=M; %Defining the third column of the matrix
Vf=[Vf_X',Vf_Y',Vf_Z']; %Creating the matrix
while Vf(:,3)<0
Vf=Vf+1;
end
disp(Vf)
The result I get is 我得到的结果是
1 2 0
-2 -1 -3
0 1 -1
1 2 0
-1 0 -2
Ideally I would like to get this result instead 理想情况下,我想获得此结果
1 2 0
1 2 0
1 2 0
1 2 0
1 2 0
The while will not start if any value is above zero to begin with and stops as soon as one value goes above zero. 如果任何值都大于零,则while不会开始,而一旦一个值大于零,它将停止。
I hope this makes sense and I have supplied enough information 我希望这是有道理的,并且我提供了足够的信息
Thank you for your time and help. 感谢您的时间和帮助。
Your current problem is that you stop iterating the very moment any of the values in the third row break the condition. 当前的问题是,在第三行中的任何值破坏条件的那一刻,您就停止了迭代。 Correct me if I'm wrong, but what I think you want is to continue doing iterations on the remaining rows, until the conditions are broken by all third columns.
如果我错了,请纠正我,但是我想您要继续对其余行进行迭代,直到所有第三列都打破了条件为止。
You could do that like this: 您可以这样做:
inds = true(size(Vf,1),1);
while any(inds)
Vf(inds,:) = Vf(inds,:)+1;
inds = Vf(:,3) < 0;
end
Of course, for the simple addition you provide, there is a better and faster way: 当然,对于您提供的简单添加,有一种更好,更快的方法:
inds = Vf(:,3)<0;
Vf(inds,:) = bsxfun(@minus, Vf(inds,:), Vf(inds,3));
But for general functions, the while
above will do the trick. 但是对于一般功能,上面的
while
可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.