For循环仅在MATLAB中采用特定值

时间:2014-06-20 13:41:03

标签: matlab for-loop

我有一个MATLAB程序,它使用两个for循环迭代最多5次。但是,我希望MATLAB只使用(1 1), (2 2), (3 3)等等。

以下是该计划:

syms l
a = [0 1 0 0 1 0;1 1 1 0 1 1;1 0 0 0 1 1;1 1 1 0 0 1;0 1 1 0 1 1];
n = [2 1;1 1;1 1;1 1;2 1];

for l = 1:5 
    for i = 1:5
        j = n(l,1);

        if a(i,j) == 0
           a(i,j:end) = circshift(a(i,j:end),[n(l,2) n(l,2)]);

           for j = n(l,1):n(l,1)+n(l,2)
               a(i,n(l,1)) = 1;
           end

        else 
           a(i,j:end) = circshift(a(i,j:end),[n(l,2) n(l,2)]);

           for j = n(l,1):n(l,1)+n(l,2)
               a(i,n(l,1)) = 0;
           end
        end

    break;
    end 

    break;
end

我希望MATLAB我的程序能够像这样工作:

first l = 1 and i = 1;
second l = 2 and i = 2;
third l = 3 and i = 3;
fourth l = 4 and i = 4;

依旧......

1 个答案:

答案 0 :(得分:1)

@RodyOldenhuis基本上回答了你的问题,我很高兴他没有把它变成一个真正的答案!

只需获取代码并更改内部for循环索引,使其与外循环索引匹配。换句话说,这样做:

syms l %// Why are you doing this?
a = [0 1 0 0 1 0;1 1 1 0 1 1;1 0 0 0 1 1;1 1 1 0 0 1;0 1 1 0 1 1];
n = [2 1;1 1;1 1;1 1;2 1];

for l = 1:5 
    i = l; %// Change here - Remove second for loop
    %// ... [rest of your code here]
    %// Get rid of the break in this loop
    end 
    %// Removed break here too
end