Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 778
neurohacker Avatar asked Jan 13 '14 09:01

neurohacker


2 Answers

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)

like image 74
Dan Avatar answered Nov 05 '22 05:11

Dan


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), []))
like image 41
Luis Mendo Avatar answered Nov 05 '22 05:11

Luis Mendo