Having trouble getting function to return two values

조회 수: 17 (최근 30일)
Patrick Keiffer
Patrick Keiffer 2018년 4월 12일
댓글: Josué Ortega 2020년 4월 6일
Hello, I wrote a simple function that takes in a wavelength as input and spits out the corresponding absorption and emission cross-sections pulled from an imported text file. The code seems to work fine but when calling the function only the first of the output variables seems to be saved. I would like the function to save both variables to the workspace so that they may be used in other code. Any ideas on what I am doing wrong? Thanks in advance. Below is my code:
function [cross_abs, cross_emm] = cross(lambda)
%This function is used to calculate the absorption cross section and
%emmision cross section for the given wavelength lambda
%Note that the unit of the lambda here should be nm
load absorption_cross.txt;
load emission_cross.txt;
%lambda=lambda*1e9;
if length(lambda)==1
if lambda>1890
cross_abs=2.181e-26; %unit is m^2
cross_emm=2.423e-25;
else
if lambda<900
cross_abs=0.5761e-24;
cross_emm=0;
end
end
cross_abs=interp1(absorption_cross(:,1)',absorption_cross(:,2)',lambda,'spline')*1e-24;
cross_emm=interp1(emission_cross(:,1)',emission_cross(:,2)',lambda,'spline')*1e-24;
end

채택된 답변

Birdman
Birdman 2018년 4월 12일
Probably you are calling function with one output argument, like
y = cross(lambda)
or none,
cross(lambda)
You should be calling like
[cross_abs, cross_emm] = cross(lambda)
  댓글 수: 2
Patrick Keiffer
Patrick Keiffer 2018년 4월 12일
Thanks, Birdman!
Josué Ortega
Josué Ortega 2020년 4월 6일
Same problem, but my function returns all cycles in a graph, so the answer is sometimes one vector, sometimes two, and so on. How to save them all if I do not know ex-ante the size of the answer?

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

추가 답변 (1개)

James Tursa
James Tursa 2018년 4월 12일
편집: James Tursa 2018년 4월 12일
Your code has a path where nothing gets assigned to the output variables. Also, even for the path that does assign the output variables, all of the if-then-else results for the output variables gets overwritten. Is this intended?
And if you call this function a lot, it is going to be slow because of the load's you execute each time it is called. Best to do this once outside the function and pass in the appropriate variables that are needed.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by