How to create a For loop for a linspace?

I have this code:
for j = 1:20
c(j) = linspace(1,10,length(j));
end
But, the result is a vector "c" with all the values "10":
c= 10 10 10 10 10 10 10....
How can I do to solve the problem? Thnaks

 Accepted Answer

Since in every iteration, ‘j’ is a scalar, the length of ‘j’ will always be 1.
I would just use:
c = linspace(1, 10, 20);
or if you actually want varying-length vectors, save ‘c’ as a cell array:
for j = 1:20
c{j} = linspace(1,10,j);
end

5 Comments

The problem is that I have to use the linespace in a "scatter" function:
for i = 1:length(temp_discesa_i)
pause(0.1)
c = linspace(1, 10, length(temp_discesa_i));
scatter(temp_discesa_i(i), spazio_discesa_i(i),30,c,'filled')
pause(0.01);
end
and Matlab give me an error: "Error using scatter (line 93) CData must be an RGB triplet, an M-by-1 vector of the same length as X, or an M-by-3 matrix."
The loop variable i is a scalar. So you're creating a scatter plot of one point with x=temp_discesa_i(i) and y=spazio_discesa_i(i) each time. In that case, the color input must be an RGB triplet or a scalar that is mapped into the colormap. In order to achieve what I think you want to do with this code, create the linspace vector prior to the for loop and index into c the same way you index into temp_discesa_i and spazio_discesa_i.
But creating a scatter plot for one point at a time seems like a bit of overkill. Are you sure you don't want to simply create a line once and update its XData, YData, MarkerFaceColor, and MarkerEdgeColor properties in the loop? Or would scatter plotting all the data at once be acceptable?
@Steven — Thank you.
I am not certain what the objective is. My suggestion is to define the colormap before the loop, as:
c = colormap(jet(length(temp_discesa_i)));
then do the plotting as:
scatter(temp_discesa_i(i), spazio_discesa_i(i),30,c(i,:),'filled')
awaiting further details.
Yes!!!! It's now working. Thank you to all.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!