How to create a function that can accommodate multiple definitions of the same variable?
조회 수: 8 (최근 30일)
이전 댓글 표시
I have the function file;
function [rateA, rateB, rateC] = FissionReactionRate(A, B, C)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
for A = [3000, 10^20, 10^14]
rateA = prod(A);
end
for B = [100, 10^20, 10^14]
rateB = prod(B);
end
for C = [1.5, 10^20, 10^13]
rateC = prod(C);
end
end
and the script file
fprintf('The first fission reaction rate is %d #/cm^3*sec', FissionReactionRate(A))
fprintf('\n')
fprintf('The second fission reaction rate is %d #/cm^3*sec', FissionReactionRate(B))
fprintf('\n')
fprintf('The third fission reaction rate is %d #/cm^3*sec', FissionReactionRate(C))
However, I am just receiving the answer
The first fission reaction rate is 100000000000000 #/cm^3*sec
The second fission reaction rate is 100000000000000 #/cm^3*sec
The third fission reaction rate is 100000000000000 #/cm^3*sec
How can I get three different answers?
댓글 수: 2
Walter Roberson
2018년 3월 4일
You define your function as expecting 3 input variables, but then you only call it with one input variable ?
And you ignore the input variables anyhow and use fixed numeric values?
And your loop ignores the current contents of the loop variable and overwrites all of the variable each time through ??
Then your function defines three outputs, but you only ever use one of the outputs ??
Krishna Bindumadhavan
2018년 3월 13일
Are you trying to multiply all the elements of a vector?
If so you can just use the built in product function prod(A) on the input vector.
I'm not sure how you were able to run the script with one argument and without defining the input - it would be great if you could give us a more detailed explanation of the use case.
Thanks!
답변 (1개)
Shree Harsha Kodi
2023년 6월 17일
In MATLAB, you cannot have multiple definitions of the same variable within the same scope. Each variable name can only be assigned a single value at any given time. However, you can create a function that accepts multiple input arguments and processes them accordingly.
댓글 수: 1
Walter Roberson
2023년 6월 17일
A = [3000, 10^20, 10^14]
A has been assigned multiple values at the same time.
참고 항목
카테고리
Help Center 및 File Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!