简体   繁体   中英

Does MATLAB offer a more elegant way to iterate through 3D array to get 3rd dimension vectors?

I'm trying to iterate trough a fixed size 3d array in order to plot the 3rd vector dimension like this:

%respo is a 3D array of fixed size defined above
for ii = 1:size(respo,1)
    for jj = 1:size(respo,2)
        plot(squeeze(respo(ii,jj,1:8)))
    end
end

Is there a better way to do this than by 2 level for loop with pointing exactly to the vector plotted at each iteration?

I get there is a linear indexing for each array in MATLAB, but I struggle to come up with a way that saves from the double-looping.

Well I guess you could reshape it to only need one loop:

respo_2D = reshape(respo, [], size(respo,3))

So now

for ii = 1:size(respo_2D, 1)
    plot(respo(ii,1:8));
end

(or potentially even plot(respo_2D(:,1:8)') depending on what you're trying to do)

plot applied to a matrix plots the columns of that matrix. So: rearrange dimensions such that the third becomes the new first and the others get combined into the new second, and then just call plot

plot(reshape(permute(respo, [3 1 2]), size(respo,3), []))

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