This is not my code, it is used from an answered question on here. How could I functionalize it?

1 Ansicht (letzte 30 Tage)
[num,txt,raw] = xlsread('p.xls') ;
P = num(:,1) ;
RV = num(:,2) ;
D = num(:,3) ;
% Pick a pressure value
Pi = input('Input pressure value:','s') ;
Pi = str2double(Pi) ;
tol = 10^-3 ;
idx = abs(P-Pi)<=tol ; % check is Pi present in data
if any(idx)
fprintf('%f is present in the data\n',Pi) ;
Pi = P(idx) ;
RVi = RV(idx) ;
Di = D(idx) ;
else
fprintf('%f is not present in the data, interpolating\n',Pi) ;
Rvi = interp1(P,RV,Pi) ;
Di = interp1(P,D,Pi) ;
iwant = [Pi RVi Di] ;
end
fprintf('Pressure = %f, R.V = %f, Liq.Density = %f\n',Pi,RVi,Di) ;

Akzeptierte Antwort

Image Analyst
Image Analyst am 27 Apr. 2022
What do you want to be an input argument? The filename? The Pi value? Any other values? Something like this maybe
function iwant = ComputeValues(filename, Pi)
iwant = []; % Initialize
[num,txt,raw] = xlsread(filename) ;
P = num(:,1) ;
RV = num(:,2) ;
D = num(:,3) ;
% Pick a pressure value
Pi = str2double(Pi) ;
tol = 10^-3 ;
idx = abs(P-Pi)<=tol ; % check is Pi present in data
if any(idx)
fprintf('%f is present in the data\n',Pi) ;
Pi = P(idx) ;
RVi = RV(idx) ;
Di = D(idx) ;
else
fprintf('%f is not present in the data, interpolating\n',Pi) ;
Rvi = interp1(P,RV,Pi) ;
Di = interp1(P,D,Pi) ;
end
iwant = [Pi, RVi, Di];
fprintf('Pressure = %f, R.V = %f, Liq.Density = %f\n', Pi, RVi, Di) ;
  2 Kommentare
ML
ML am 28 Apr. 2022
I want the input argument to be the "user input" pi, as for the file I just need it there so it can be compared to the input. Sorry not sure if that makes sense....
Image Analyst
Image Analyst am 28 Apr. 2022
You can certainly use the input() function wherever you want to get a value for Pi or any other variable. You can use it both in your main program before you call the function to get input argument values that you are going to pass. You can also use it in the function if you need to get additional values.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by