0

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
1
  • plot(YourMatrix(:,1:end)) for each column and plot(YourMatrix(1:end,:)) for each row. Commented Dec 11, 2015 at 9:23

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Very nice thanks! I was wondering is there also a nicer way of filling the matrix b? Is there a way of specifying just the row to fill or do I have use the full indexing notation b(i:i,1:nGrid) =?
@Riggs You're welcome! Unfortunately the first parameter has to be a scalar and so you need to use a loop...yup...sucks. However, you can shorten the loop to just do this: for i = 1:nNu, b(i,:) = besselj(nu(i), xLine); end. It's slightly shorter, but it does the same trick. You don't need to do i:i. That's superfluous. Just use i by itself. Also, instead of 1:nGrid, just use :. xLine has nGrid elements, so the output will implicitly be nGrid elements long.
2

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).')

2 Comments

My comment was nonsense. It looks like that column stuff I talked about has changed. This is good. +1.
@rayryeng Probably good style though to transpose b for compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.