Problem with vectors and if statements
Ältere Kommentare anzeigen
Hello everyone, I am trying to write a function that takes in a value of N and a vector x and run the vector through an if statement to sort the numbers and plot them accordingly. I want all plots on the same graph.
function [ blah] = tanplot( x,N)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
hold on
if abs(tan(x)) <= N
y = tan(x);
plot(x,y)
elseif tan(x) > N
y = N;
plot(x,y,'-m')
elseif tan(x) < -N
y = -N;
plot(x,y,'-r')
end
hold off
title('Tan Plot')
end
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 20 Sep. 2015
1 Stimme
"if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
In your case some of the vector elements satisfy abs(tan(x)) <= N and other elements do not, so the result of your expression contains a mix of values that are zero and nonzero, so the expression is considered false.
Your code wants to produce three different plots, each dependent upon a condition that is true for some elements and false for other elements. Your "if" will never be true for all elements simultaneously, so your code will not plot anything. As long as you define your code in terms of three different plots instead of in terms of three different ways to determine the value to be plotted for any given point, you will not be able to produce a graph.
While you think about that I suggest you read http://blogs.mathworks.com/steve/2008/01/28/logical-indexing/
Kategorien
Mehr zu Title finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!