Multiple loop variables Matlab

前端 未结 3 704
北海茫月
北海茫月 2020-12-21 12:28

In C++/C, we have multiple loop variables in a single loop, like for(int i=0; int j=0; i<5; j<5; i++; j++) Is there any facility in Matlab

3条回答
  •  爱一瞬间的悲伤
    2020-12-21 13:11

    As chappjc pointed out, and as MathWorks states in the documentation, each iteration of a for loop takes the next column of the iterator. Thus, to iterate through a column vector, for example, one must transpose it (i.e. for ii = [1; 1; 2; 3; 5]'), otherwise ii is equal to the column vector, all at once.

    And merely to extend chappjc's excellent answer, you may take advantage of this behavior with cells, also, where you might have some differently sized strings, in addition to wanting a numeric iterator, and then you can deal them to variables so you don't have to do as much indexing. Here is a crude example:

    figure(1)
    imageList = {};
    for ii = [{somePath; someDirListing; 1}, {anotherPath; anotherDirListing; 2}] % Each iteration takes one column
    
        [pathname, images, iPos] = deal(ii{:});
    
        for iImage = images
            img = imread(fullfile(pathname, iImage));
            imagesc(img)
            axis image
            if iPos == 1
                title(['This is a left image, titled ' iImage])
            else
                title(['This is a right image, titled ' iImage])
            end
            pause(1)
        end
    end
    

提交回复
热议问题