plot different parts of vector

조회 수: 4 (최근 30일)
Robin Strak
Robin Strak 2020년 3월 17일
댓글: Sriram Tadavarty 2020년 3월 17일
I´ve got a vector M(1x80) and would like to plot four different graphs (graph 1 equals values 1:20, graph 2 values 21:40, ...) and have a name of each of them in the legend (including a trendcurve):
I thougt of a loop like that:
for i = 1:20:80
plot(M3(i);
legend('Graph 1');
end
Can you tell me where the error is?
Thanks a lot for helping me!

채택된 답변

Sriram Tadavarty
Sriram Tadavarty 2020년 3월 17일
편집: Sriram Tadavarty 2020년 3월 17일
Hi Robin,
The following code will provide what you are looking for
M3 = rand(1,80);
j = 1;
str = [];
for i = 1:20:80
hold on
plot(M3(i:19+i)); % Update this to have 20 values, which is fixed to 1 in your code
str = [str ["Graph " + num2str(j)]]; % To have different legend for each plot through string array
j = j+1;
end
legend(str)
Hope this helps.
Regards,
Sriram
  댓글 수: 4
Robin Strak
Robin Strak 2020년 3월 17일
Thanks, Sriram, it works now :)
Maybe you could help me with a further question:
As I added a trendline to every graph I wanted the graph and the trendline to have the same colour. I tried to come up with 4 different colours in "col" , add them to the plots and increment them after every loop, but Matlab doesnt like the "k" argument in colour.
k =1;
col = {'g', 'y', 'c', 'm'};
for i = 1:20:80
plot(M_3(i:19+i), col(k));
str = [str ["Graph " + str(j)]];
c_rms = polyfit(time,M_3(i:19+i),1);
y_est = polyval(c_rms,time);
hold on
plot(time,y_est, col(k) 'LineWidth',2)
j = j+1;
k = k+1;
Do you know what I need to change?
Sriram Tadavarty
Sriram Tadavarty 2020년 3월 17일
Hi Robin,
Please do accept the answer, if helped.
Here, col is the cell array and it need to be accessed through curly brackets {} rather than open bracket (k).
I am not sure what the variable time is.
Use col{k} instead of col(k), it solves the issue. Here is a partial code
col = {'g', 'y', 'c', 'm'};
for i = 1:20:80
plot(M_3(i:19+i), col{k});
str = [str ["Graph " + num2str(j)]];
c_rms = polyfit(1:20,M_3(i:19+i),1);
y_est = polyval(c_rms,1:20);
hold on
str = [str ["Polyfit " + num2str(j)]];
plot(y_est, col{k}, 'LineWidth',2)
j = j+1;
k = k+1;
end
legend(str)
This should provide some insights of how to solve this. I suggest you to start a new question, if there is any other problem.
Thanking you
Regards,
Sriram

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by