What's the error in my code?

조회 수: 6 (최근 30일)
Christopher
Christopher 2015년 2월 2일
편집: Stephen23 2015년 2월 4일
I can't seem to plot this function I wrote. What is wrong with it? Thanks in advance!!
function [] = Apple(D,T)
x= linspace (0,30,3000);
y=0;
for i = 0:6;
if x > (i*T) && x < ((T*i)+(D*T))
y(x)= 1;
elseif y(x) == 0;
end
end
plot(x, y(x));
ylim([-.25,1.25])
end
  댓글 수: 2
Matt J
Matt J 2015년 2월 2일
편집: Matt J 2015년 2월 2일
You forgot to describe what's not working, e.g., how to run it and any error messages it displays.
Stephen23
Stephen23 2015년 2월 2일
Please learn about vectorization !

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

답변 (2개)

Michael Haderlein
Michael Haderlein 2015년 2월 2일
x > (i*T) && x < ((T*i)+(D*T))
You cannot use && in case of arrays. Use & instead.
if x > (i*T) && x < ((T*i)+(D*T))
You cannot use arrays as condition for the if structure. What should the program do if some elements of the array are true and some are false?
elseif y(x) == 0;
Again, that's an array as condition which doesn't work. Additionally, x is not an appropriate index (only values 1, 2, 3, and so on are allowed).

Stephen23
Stephen23 2015년 2월 2일
편집: Stephen23 2015년 2월 4일
Here is a short list of some of the syntax errors and poor coding. Some of these prevent it from working:
  1. MATLAB has one-based indexing . The code y(x) tries to obtain the zeroth element (as x(1)==0), which is invalid in MATLAB.
  2. Logical short-circuit operators || and && require scalar logical values, not arrays as they are here: x > (i*T) && x < ((T*i)+(D*T)). Because x is an array, x>n will also be an array, and so the syntax x<n && ... will always be an error.
Others are just things that really could be done much much better:
  1. Array preallocation before the loop: y probably needs to be defined to be the same size as x.
  2. Pay attention to the editor code warnings : it shows one warning with the version I am using.
  3. Variable name i should be avoided, as this is the name of the inbuilt imaginary unit .
  4. The use of a for loop, when this simple code should really be vectorized .
Without knowing exactly what your aim is, it is hard to know how to "fix" this code, as it is very unclear.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by