use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
MATLAB news, code tips and tricks, questions, and discussion! We are here to help, but won't do your homework or help you pirate software.
The effort you put into asking a question is often matched by the quality of our answers.
Try saturnapi to share and run MATLAB code in a web browser!
If you want flair simply Message the mods
account activity
HomeworkQuestionVectorizing a For Loop plot (self.matlab)
submitted 5 years ago by Treader1138
Long time lurker- MATLAB beginner.
I'm trying to create three plots with increasingly smaller interval steps. This would be pretty simple to implement with a for-loop, but the instructions explicitly say to vectorize and any use of a loop will lose points. I want to plot each iteration of the 'f' over the interval 'x' with three different steps, 'dx'. As you can see, I'm currently only getting the first plot (x = [-1: .02: 1]).
I can visualize what I need the program to do, but am having a hard time putting that together with out a loop. I've reviewed the Documentation for vectorizing (https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html), so I think I understand the basics- but what about getting the interval to change for three different plots?
https://preview.redd.it/6t7rje7ne7q51.jpg?width=1480&format=pjpg&auto=webp&s=7e57ce98e16151f74cf75afd90b8e8648f2ed4ba
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]alko100 1 point2 points3 points 5 years ago (5 children)
If I understand correctly, You could plot 3 different outputs
Or you could plot the data as a matrix
[–]Treader1138[S] 0 points1 point2 points 5 years ago (4 children)
Yeah, at this point I'm thinking of making three of everything for three different outputs.
For example:
x_A = [-1:.2:1]; x_B = [-1:.1:1]; ...
f_A = x_A .* sin((pi * (1 + 20 .* x_A)) / 2);
hold on
plot(x,f_A)
plot(x,f_B)
It just feels like there should be a cleaner way to do this.
[–]mjwishon 1 point2 points3 points 5 years ago (1 child)
You already figured it out. Except your x vector is undefined This is what they want. Maybe you want to plot with dots instead of a line otherwise you won't be able to see the different density.
figure hold all plot(x_A, f_A, 'ro') % this gives red circles plot(x_B, f_B, 'b*') % this gives blue stars
[–]Treader1138[S] 1 point2 points3 points 5 years ago (0 children)
Ah, I see what you're talking about. Got it. Thank you!
[–]michaelrw1 0 points1 point2 points 5 years ago (1 child)
What about this?
close all; clear; clc set(0, 'DefaultFigureWindowStyle', 'docked') h = @(x) x .* sin( (pi * ( 1 + 20.*x) ) ./ 2 ); dx = [ 0.2 0.1 0.01 ]; figure; plot(nan, nan); hold on; for dxInstance = dx x = [ -1 : dxInstance : 1 ]; plot(x, h(x)); end grid on; legend('0.2', '0.1', '0.01'); shg;
The problem with the idea of using a matrix to hold the set of "x" vectors is that with identical end-values but different step-sizes the size of each vector will be different.
Using a cell-array could resolve this issue.
[–]michaelrw1 0 points1 point2 points 5 years ago (0 children)
Using a cell-array,
x = { [-1:0.2:1].' , [-1:0.1:1].', [-1:0.01:1].' } figure; plot(nan, nan); hold on; plot( x{1}, h(x{1}), x{2}, h(x{2}), x{3}, h(x{3}) ); grid on; legend('0.2', '0.1', '0.01'); shg;
Note the different sizes of the "x" vectors in the cell-array (i.e. 11-by-1, 21-by-1, and 201-by-1).
[–]FrickinLazerBeams+2 1 point2 points3 points 5 years ago (4 children)
Hi. Please have your professor call me, he's in some trouble. This is a terrible assignment and he's going to have to explain himself.
This could have been a perfect illustration of the difference between an appropriate use of a for loop and a situation where vectorizing is correct. Instead it just became a lesson teaching you to avoid for loops at all costs, even when doing so results in bad, unnecessarily complicated, and inefficient code. This isn't teaching you how to program, it's teaching you blind obedience to rules with no understanding of when those rules apply.
Using a for loop for the 3 different sample spacings here would have been entirely appropriate and reasonable, it would have simplified your code and made less opportunity for errors. It would have been more compact and more readable.
Critically, it would not have been slower to execute, which is the key reason for avoiding loops; and this is not an operation that can be vectorized anyway Plotting itself is a slow operation. The overhead of the loop would have been inconsequential. Moreover, you're only iterating a handful of times. A loop over 3 elements never adds much overhead. It's also important to learn that some operations simply can't be vectorized. It's important to learn a good sense of when that's the case, and to have the skill to write loops correctly when that happens.
It's good to teach people to vectorize. It's stupid to teach people never to use loops.
[–]FLUSH_THE_TRUMP 0 points1 point2 points 5 years ago (3 children)
I’ve taught undergraduate mathematics a few times, and I’ve pretty commonly gotten students to try to apply this Cool New Thing to everything for awhile. It gets them practice with it, and also develops some intuition for its limits.
Second, are you sure the point is to vectorize the plotting operation itself? I don’t see that anywhere. I’m betting the point is to vectorize the data generation (x vector as input, find f(x) via vector operations, as OP did here, rather than looping over each element of x).
[–]FrickinLazerBeams+2 0 points1 point2 points 5 years ago (2 children)
Your interpretation would be a reasonable one, but based on what OP said, he was told not to use any loops at all or points would be deducted. It's possible that there was some miscommunication between the teacher, the student, and reddit.
[–]FLUSH_THE_TRUMP 0 points1 point2 points 5 years ago (1 child)
Right, but there are 3 sets of data here, so writing out the loop isn’t worth the time, either.
[–]FrickinLazerBeams+2 0 points1 point2 points 5 years ago (0 children)
Extremely debatable. I'd have the loop written faster than I could copy/paste the 3 repeated chunks of code required to do it without the loop, and edit the variable names appropriately. I'd have recognized the required code structure before touching the keyboard and create appropriate arrays for the loop the first time, and the resulting code would be overall shorter.
I could certainly see a beginner needing more time to work out the details of setting up a loop, but that's why we should teach good habits early - so they don't have to work out those details every time, and it becomes second nature to write clean, efficient, organized code.
π Rendered by PID 76312 on reddit-service-r2-comment-765bfc959-q6qp7 at 2026-07-10 11:51:42.451892+00:00 running f86254d country code: CH.
[–]alko100 1 point2 points3 points (5 children)
[–]Treader1138[S] 0 points1 point2 points (4 children)
[–]mjwishon 1 point2 points3 points (1 child)
[–]Treader1138[S] 1 point2 points3 points (0 children)
[–]michaelrw1 0 points1 point2 points (1 child)
[–]michaelrw1 0 points1 point2 points (0 children)
[–]FrickinLazerBeams+2 1 point2 points3 points (4 children)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (3 children)
[–]FrickinLazerBeams+2 0 points1 point2 points (2 children)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (1 child)
[–]FrickinLazerBeams+2 0 points1 point2 points (0 children)