Help with User defined function

5 visualizaciones (últimos 30 días)
Sam Horigan
Sam Horigan el 6 de Mayo de 2021
Editada: Walter Roberson el 6 de Mayo de 2021
Could someone please explain how to write the first lines of a user definded function in Matlab?
including:
function [y] = UnitConversionsFunction(x,)
what do u put after the (x,...) if i am making a function full of unit conversions.
%unit conversions
switch
case 'c2f'%cel to fah
y=(x*9/5)+32;
case 'f2c'%fah to cel
y=(x-32)*5/9;
case 'mil2fo'%milliltres to fluid ounce
y= x/29.5735;
case 'fo2mil'%fluid ounce to millilitres
y= x*29.5735;
case 'l2p'%litre to pints
y= x*1.75975;
case 'p2l'%pints to litres
y= x/1.75975;
case 'l2g'%litres to gallons
y=x/4.54609;
case 'g2l'%gallons to litres
y= x*4.54609;
case 'kilj2kilc' %kiloj to kiloc
y=x/4.184;
case 'kilc2kilj'%kiloc to kiloj
y= 4.184*x;
case 'pas2psi' %pas to psi
y= x/6894.76;
case 'psi2pas' %psi to pas
y= x*6894.76;
end
Thanks

Respuestas (1)

Subhadeep Koley
Subhadeep Koley el 6 de Mayo de 2021
Editada: Subhadeep Koley el 6 de Mayo de 2021
function y = UnitConversionsFunction(x, options)
% Validate that value is a character vector or string scalar. (Works only with R2020b or above)
mustBeTextScalar(options)
% Convert to lowercase
options = lower(options);
%unit conversions
switch options
case 'c2f'%cel to fah
y =(x*9/5)+32;
case 'f2c'%fah to cel
y =(x-32)*5/9;
case 'mil2fo'%milliltres to fluid ounce
y = x/29.5735;
case 'fo2mil'%fluid ounce to millilitres
y = x*29.5735;
case 'l2p'%litre to pints
y = x*1.75975;
case 'p2l'%pints to litres
y = x/1.75975;
case 'l2g'%litres to gallons
y=x/4.54609;
case 'g2l'%gallons to litres
y = x*4.54609;
case 'kilj2kilc' %kiloj to kiloc
y = x/4.184;
case 'kilc2kilj'%kiloc to kiloj
y = 4.184*x;
case 'pas2psi' %pas to psi
y = x/6894.76;
case 'psi2pas' %psi to pas
y = x*6894.76;
otherwise
error('Please enter correct option')
end
end
Invoke the function like,
res = UnitConversionsFunction(10, "f2C")

Categorías

Más información sobre NaNs en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by