필터 지우기
필터 지우기

Plot for different conditions of function

조회 수: 9 (최근 30일)
Sara Boznik
Sara Boznik 2020년 8월 14일
댓글: Rik 2020년 8월 14일
Hi everyone,
i have the task that I have to make plot for different conditions y(x) for different value x.
The following code I have is below. If is correct.
But plot did not work. I thought that missing hold on or something like that but also did not work.
clear all
close all
clc
x=rand
if x<6
y=2;
% fprintf ('%.2f, %d\n',x,y)
elseif x>=6 & x<20
y=x-4;
% fprintf ('%.2f, %.2f\n',x,y)
elseif x>=20
y=36-x;
% fprintf ('%.2f, %.2f\n',x,y)
end
fprintf ('%.2f, %.2f\n',x,y)
for x=-30:1:30
if x<6
y1=2;
plot(x,y1)
elseif x>=6 & x<20
y2=x-4;
plot(x,y2)
elseif x>=20
y3=36-x;
plot(x,y3)
end
end
Thank you!

채택된 답변

Rik
Rik 2020년 8월 14일
편집: Rik 2020년 8월 14일
Your code is plotting scalars. If you want to see a line you should put in multiple values at the same time.
for x=-30:1:30
if x<6
y1=2;
plot(x,y1,'.')
elseif x>=6 & x<20
y2=x-4;
plot(x,y2,'.')
elseif x>=20
y3=36-x;
plot(x,y3,'.')
end
end
A better strategy would be to create the entire array at one, and then plot it as a vector.
x=-30:30;
y=NaN(size(x));
L=x<6;
y(L)=2;
L=x>=6 & x<20;
y(L)=x(L)-4;
L=x>=20;
y(L)=36-x(L);
plot(x,y)
Also, you shouldn't use clc,clear all,close all. You aren't printing anything to the command window, you should only use clear all exactly once in your entire code base, and you don't want to close all figures without knowing they are related to your code.
  댓글 수: 2
Sara Boznik
Sara Boznik 2020년 8월 14일
Thank you so much, it works.
Actually that is for school and they thaught us that we have to write clear all, close all, clc everytime.
Rik
Rik 2020년 8월 14일
That is a bad habit. If your instructor doesn't agree, feel free to refer them to me (or many others on this site for that matter).
If you don't understand what these commands do you shouldn't be using them. There is a valid case to make to start instructional scripts with clc,clear,close, maybe even close all (e.g. the demo that Image Analyst often adapts), but especially clear all is an indication that the linter is ignored, a bad habit.
It is much better to teach why and when you should use these commands than simply require them for every single script.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by