简体   繁体   中英

Increment a for loop by 3 then by 1 using matlab

I am working on MATLAB code right now, and I want to increament y by 3 then by 1 and so on.

Here is the code if anyone could help, it would be appreciated.

for y=1:2:9
    for x=9:-1:1
        A(x,y)=1
        if x==1 && y~=9 
            %y=y+1
            for x= 1:9
                A(x,y)=1
            end
        end
    end
end

You first make a vector of the indexes you want to visit and then loop over the vector.

idx = [1,2,5]; %and so on
for ct = 1:length(idx)
    A(x,y(idx(ct)))=1
end

You can specify a predefined vector or even matrix to be used in for loop; not necessary to use range index.

I am not completely certain how your question is reflected in your code. However, if you want to alternately increment y with 1 and 3, I would make a standard for-loop and then update y inside. Something like:

n = 100;
for i = 1:n
    y = y + 2*mod(i,2)+1;
    display(y) %Do things
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM