Ron Ronson
Ron Ronson

Reputation: 505

Is it possible to plot rows of a matrix without a for loop?

I have a matrix that stores multiple functions in its rows each evaluated against the interval [0,20]. I'm running through a for loop to output them at the moment. Is there a better way of doing this or is this the only way of doing it in MATLAB?

h = 0.1;
xLine = 0:h:20;
nGrid = length(xLine);

nu = [ 1, 2, 3 ];
nNu = length(nu);

b = zeros(nNu,nGrid);
for i=1:nNu
    b(i:i,1:nGrid) = besselj(nu(i), xLine);
end

hFig = figure(1);
hold on
set(hFig, 'Position', [1000 600 800 500]);
for i=1:nNu
    plot(xLine, b(i:i,1:nGrid))
end

Upvotes: 0

Views: 597

Answers (2)

Matthew Gunn
Matthew Gunn

Reputation: 4519

Replace for loop with:

plot(xLine, b(:,1:nGrid))

Note: I can't perfectly recall but some older versions of Matlab may want everything in columns and you'd want to transpose the matrices:

plot(xLine.', b(:,1:nGrid).')

Upvotes: 2

rayryeng
rayryeng

Reputation: 104535

You can use plot vectorized. Specifically, you can supply b directly into plot but you need to make sure that the larger of the two dimensions in b matches the total number of elements in the vector xLine. This is what you have, so we're good. Therefore, because each unique signal occupies a row in your matrix, just supply b into your plot call and use it a single time.

hFig = figure(1);
hold on
set(hFig, 'Position', [1000 600 800 500]);
plot(xLine, b);

This will plot each row as a separate colour. If you tried doing this, you'll see that the plots are the same in comparison to the for loop approach.

Check out the documentation for plot for more details: http://www.mathworks.com/help/matlab/ref/plot.html

Upvotes: 4

Related Questions