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
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
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
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.

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by