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

 채택된 답변

Torsten
Torsten 2023년 1월 22일
편집: Torsten 2023년 1월 22일

0 개 추천

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

Stephen23
Stephen23 2023년 1월 22일
And get rid of CLEAR, CLOSE ALL, CLC.
Thank you for reply. what would be the name of this function?
Torsten
Torsten 2023년 1월 22일
fun
I got you. thank you so much for your help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

질문:

2023년 1월 22일

댓글:

2023년 1월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by