Alan B.
Alan B.

Reputation: 59

Plot multiple 2D graphs stored as a 3D matrix

I need to combine a fair amount (~15000) of plots on a single figure. Doing it iteratively would take forever, so I stored all my data in a 3D matrix hoping I could plot all my data at once.

My matrix structure is as following : Matrix structure

So, if I want to display the first plot of my matrix M, I type :

plot(M(:,1,1),M(:,2,1))

Naturally, to plot all my data at once, I tried :

plot(M(:,1,:),M(:,2,:))

Which gives me the following error:

Error using plot
Data cannot have more than 2 dimensions.

Any ideas on how I could find a fast way to plot this kind of data?

Here is a code sample:

M = rand(5,2,3);

for i = 1:1:size(M,3)
    M(:,1,i) = linspace(1,size(M,1),size(M,1));
%     plot(M(:,1,i),M(:,2,i))  % Plot iteratively --> Works but slow
%     hold on 
end

plot(M(:,1,:),M(:,2,:)) % --> Gives the error 'Data cannot have more than 2 dimensions.'

Upvotes: 1

Views: 574

Answers (1)

Dev-iL
Dev-iL

Reputation: 24169

The simplest solution is to squeeze your data, as it is inherently 2D, but merely permuted:

plot( squeeze(M(:,1,:)), squeeze(M(:,2,:)) )

A matrix like M(:,1,:) is of size 5x1x3, and what squeeze does is remove the intermediate dimension of size 1, yielding a 5x3 matrix. This can also be acheived using permute(M(:,1,:), [1,3,2]).

Upvotes: 2

Related Questions