How to formulate the following conditional function?

Consider the following function,f:
if x=0:
f(x)=0
else:
f(x)=sin(1/x)
how to formulate that as a Matlab M-File function?
thanks?

2 comentarios

moh - you state that f is a function but perhaps it is an array instead? are you passing in x to this function and expect to get something returned? Is x an integer or real number? Please provide more details.
f is a function and x is a real number.

Iniciar sesión para comentar.

 Respuesta aceptada

This works:
function output = f(x)
output = sin(1 ./ x);
% Zero out any values where x is exactly zero.
output(x == 0) = 0;
% Note, this works regardless if x is a scalar or a vector or matrix.
To call it, here is an example:
x = randi(5, 6, 6) - 1
output = f(x)

4 comentarios

I cann't understand your answer.
Would you please give me the exact definition of f(x) in Matlab language, so I could copy and paste it to the Matlab M-file editor and check the output of the function.
Thanks.
Image Analyst
Image Analyst el 26 de Ag. de 2018
Editada: Image Analyst el 26 de Ag. de 2018
Attached is a script that works for scalar, vector, and matrix. Copy and paste into a script, like test.m, like I did with the attached.
clc; % Clear the command window.
clearvars;
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;fontSize = 22;
% x is a scalar
x = 5
output = f(x)
% x is a vector
x = randi(5, 6, 6) - 1
output = f(x)
% x is a matrix
x = randi(5, 6, 6) - 1
output = f(x)
function output = f(x)
output = sin(1 ./ x);
% Zero out any values where x is negative
output(x == 0) = 0;
% Note, this works regardless if x is a scalar or a vector.
end
To integrate output, you could either sum up the values or use trapz() - whichever algorithm you want.
area = sum(output);
area = trapz(x, output);
the key point in your script that I missed, is:
output(x == 0) = 0;
would you please suggest a book to read more about Matlab.
thanks

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.

Productos

Versión

R2011a

Etiquetas

Preguntada:

el 26 de Ag. de 2018

Comentada:

el 27 de Ag. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by