MATLAB: How to convert m code file script to a function for using in excel add-Ins

how to make and call a function

I want to create a function for following code to use it into excel add-Ins or to use in application complier.
My Inputs for the code can be provided by user or can be read from excel file as mentioned in code.
My output is SoCeR and Power_con matrix only.
clear all;
B_Cap = [4;4;4]; % Input 1
B_Capacity = B_Cap(1);
N_F_eR = 40; %Input 2
N_ch = 25; % Input 3
N_P_eR = 20; % Input 4
Ch_r = 3.3;
C_rate = 1; % Input 5
RTE = 0.99;
SoCi = 0.25; % Input 6
SoCf = 0.95;
P_slot = Ch_r*C_rate*0.5*RTE;
Soc_eR = P_slot/B_Capacity;
for i=1:15
N_EV(i)= randi(10,1,1); % Input 7 ( Can be read with eisitng excel file )
end
cell_EV=cell(15,1);
for i=1:15
if N_EV(i)~=0
for j=1:N_EV(i)
pos(j) = randi(length(B_Cap));
cap(j) = B_Cap(pos(j)); % capacity selection for each EVs
end
cell_EV{i,1} = cap;
pos=[];
cap=[];
else
cell_EV{i,1} =0;
end
end
SoCeR = [];
for i=1:N_F_eR
SoC_eR(i)= 1;
SoC_ceR = SoC_eR';
SoCeR(i,1) = SoC_ceR(i);
end
for i=1:N_P_eR
x1 = 0.40; %min
y1 = 0.60; %max
SoCp_eR(i)= (y1-x1).*rand(1,1) + x1;
SoCp_ceR = SoCp_eR';
SoCeR(end+1,1) = SoCp_ceR(i);
end
%% check status initially
[index1, idx1] = find(SoCeR==1) ;
[index2, idx2] = find(SoCeR<1);
counteR = sum(idx1) ;
N_F_eR = counteR;
N_P_eR = sum(idx2);
IDX2 = cell2mat(cell_EV(1))==B_Capacity;
S_eR = sum(IDX2);
%% for t=1
IDX2 = cell2mat(cell_EV(1))==B_Capacity;
S_eR(1) = sum(IDX2);
if S_eR(1) <= counteR % MAX vehicle can swap in 30min and swap min available condition
SoCeR(:,1)=SoCeR(:,1);
Temp = SoCeR(:,1);
for j=1:S_eR(1)
Temp(index1(j))= []; % replacing 1 by SoCi
Temp(end+1,1) =SoCi;
end
else
end
SoCeR(:,1)=Temp; % OUTPUT 1
Power_con(1)=N_P_eR*P_slot; % OUTPUT 2
%% more code for loop t=2:15 to calculating the SoCeR(60*15) and Power_con(1*15) at the end of code
How to convert this code to a function based and get outputs.
File name is data.m

Best Answer

Put the keyword "function" on the first line, get rid of clear all, and make sure you don't define any of the input variables or else it will ignore whatever the user passed in.
function [SoCeR, Power_con] = CalculatePower(B_Cap, N_F_eR, N_ch, N_ch, C_rate, SoCi)
% Now, don't define any of those input arguments inside the function or you will blow away what the user passed in!!!
B_Capacity = B_Cap(1);
To call, assign the initial values for B_Cap, N_F_eR, N_ch, N_ch, C_rate, and SoCi in your main/calling program, then call CalculatePower():
[SoCeR, Power_con] = CalculatePower(B_Cap, N_F_eR, N_ch, N_ch, C_rate, SoCi)
Related Question