Matlab中每行每一列的双循环 [英] Double loop for each column per row in matlab
问题描述
下面的代码完成了应做的事情,并且只占用一列.
The following code does what it should and works of one column.
%% Working loop
z = HongKongPrices(1:end,114);
zeros = false(size(z));
r = size(z,1);
c = size(z,2);
for i = 5:r
if z(i) == z(i-4) && z(i) == z(i-3)
zeros(i-3:i) = 1
end
end
z(zeros) = NaN
我试图为HongKongPrices在每列的基础上执行for循环,但是以下代码失败(出于时间原因,我从三列开始).
I am trying to execute the for-loop on a per column basis for HongKongPrices, however the following code fails (I am starting with three columns for time reasons).
%% Non workling loop
z = HongKongPrices(1:end,[80 85 115]);
zeros = false(size(z));
r = size(z,1);
c = size(z,2);
for k = 1:c
x = z(1:end,k)
for i = 5:r
if x(i) == x(i-4) && x(i) == x(i-3)
zeros(i-3:i) = 1
end
end
end
x(zeros) = NaN
推荐答案
您根本不需要变量x
.您可以在if
语句中使用逻辑索引.代替x(i)
,使用x(i,k)
,依此类推.当然,您必须对zeros
做同样的事情.
You don't need the variable x
at all. You can use logical indexing in you if
statement. Instead of x(i)
, use x(i,k)
and so on. Of course you have to do the same with zeros
.
z = HongKongPrices(1:end,[80 85 115]);
zeros = false(size(z));
r = size(z,1);
c = size(z,2);
for k = 1:c
for i = 5:r
if z(i,k) == z(i-4,k) && z(i,k) == z(i-3,k);
zeros(i-3:i,k) = 1
end
end
end
z(zeros) = NaN;
PS:zeros
是Matlab函数,因此最好使用另一个变量名.这样,您将无法在代码中使用zeros
函数.
PS: zeros
is a Matlab function, so it would be better to use another variable name. Like this you won't be able to use the zeros
function in your code.
这篇关于Matlab中每行每一列的双循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!