Borrar filtros
Borrar filtros

Hoe can I convert my script to a function?

2 visualizaciones (últimos 30 días)
Behrooz Daneshian
Behrooz Daneshian el 22 de En. de 2023
Comentada: Behrooz Daneshian el 22 de En. de 2023
Hi all,
I coded an script. I want to convert it to fuction so that I can call it whereever it is needed. Could you please guide me how to do that correctly? The inputs of the fuction are Alpha and Mu, and the output is supposed to be lambda.
clear
close all
clc
load("Coefficient.mat")
Alpha=2;
Mu=[0.2 0.4 0.8];
Alpha_vector=Coefficient(:,2)+Coefficient(:,3).*Mu+Coefficient(:,4).*(Mu.^2)+Coefficient(:,5).*(Mu.^3)+Coefficient(:,6).*(Mu.^4)...
+Coefficient(:,7).*(Mu.^5)+Coefficient(:,8).*(Mu.^6);
Mu_max=[10 10 10 10 10 9 8 sqrt(42) sqrt(30) 5 sqrt(20) sqrt(12) 3 sqrt(6) 2.1040 1.6818 1.4142 0.9487 0.7483 0.6...
0.4472 0.4 0.3464 0.27 0.22 0.1414];
lambda_min=[0.57 0.46 0.4 0.35 0.32 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3];
lambda=zeros(1,length(Mu));
for t=1:length(lambda)
if Alpha>8 && Mu(t)>=Mu_max(26)
lambda(t)=lambda_min(26);
elseif Alpha>8 && Mu(t)<Mu_max(26)
lambda(t)=Alpha_vector(26,t);
else
for k=1:length(Coefficient(:,1))
if ismembertol(Alpha, Coefficient(k,1), 1e-8) && Mu(t)>=Mu_max(k)
lambda(t)=lambda_min(k);
elseif ismembertol(Alpha, Coefficient(k,1), 1e-8) && Mu(t)<Mu_max(k)
lambda(t)=Alpha_vector(k,t);
elseif Alpha>Coefficient(k,1) && Alpha<Coefficient(k+1,1) && Mu(t)>=Mu_max(k)
lambda(t)=lambda_min(k);
elseif Alpha>Coefficient(k,1) && Alpha<Coefficient(k+1,1) && Mu(t)<Mu_max(k)
lambda(t)=interp1([0:0.1:1, 1.2:0.2:2, 2.5:0.5:6, 7, 8], Alpha_vector(:,t), Alpha);
end
end
end
end

Respuesta aceptada

Torsten
Torsten el 22 de En. de 2023
Editada: Torsten el 22 de En. de 2023
If the coefficients don't change in the course of the simulation, you should read "Coefficient.mat" only once and pass the matrix to "fun" together with "Alpha" and "Mu".
function lambda = fun(Alpha,Mu,Coefficient)
% Insert your script
end
  4 comentarios
Torsten
Torsten el 22 de En. de 2023
fun
Behrooz Daneshian
Behrooz Daneshian el 22 de En. de 2023
I got you. thank you so much for your help.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by