Borrar filtros
Borrar filtros

Multiple inputs/outputs of a function

2 visualizaciones (últimos 30 días)
Kyle Langford
Kyle Langford el 10 de Mzo. de 2021
Comentada: Kyle Langford el 12 de Mzo. de 2021
I have my function defined as:
function [x,y] = get_y(x)
if x<-1;
y=exp(x+1);
else
if (-1<x & x<5);
y=2+cos(pi*x);
else x>=5;
y=10*(x-5)+1;
end
end
end
when I individually run x=-2 or x=8, I get the correct answer.
When i run x=[-2,8], it only gives me answers based on the 3rd parameter. How do I get the correct output parameterized by the input?

Respuesta aceptada

ANKUR KUMAR
ANKUR KUMAR el 10 de Mzo. de 2021
Editada: ANKUR KUMAR el 10 de Mzo. de 2021
You can use the same function which you provided, and use loop while calling the function, or you can modify the function to give output as per your input.
IDEA 1: Using the same code which you provided:
Calling the function:
input_array=[-2,8];
for index=1:length(input_array)
[a(index),b(index)]=get_y(input_array(index));
end
a
b
Function:
function [x,y] = get_y(x)
if x<-1;
y=exp(x+1);
else
if (-1<x & x<5);
y=2+cos(pi*x);
else x>=5;
y=10*(x-5)+1;
end
end
end
IDEA 2: You can prefer to nodify the function itself.
Calling the function:
[xx,yy]=get_y_advance(input_array);
xx
yy
Function:
function [x_array,y_array] = get_y_advance(input_array)
for index=1:length(input_array)
x=input_array(index);
if x<-1;
y=exp(x+1);
else
if (-1<x & x<5);
y=2+cos(pi*x);
else x>=5;
y=10*(x-5)+1;
end
end
x_array(index)=x;
y_array(index)=y;
end
end
  1 comentario
Kyle Langford
Kyle Langford el 12 de Mzo. de 2021
Awesome, thank you! I like how the first one turned out. I was getting really frustrated trying to get the code smoothed out.

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by