How to create a function that can accommodate multiple definitions of the same variable?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Walter Roberson
am 4 Mär. 2018
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
am 13 Mär. 2018
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!
Antworten (1)
Shree Harsha Kodi
am 17 Jun. 2023
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 Kommentar
Walter Roberson
am 17 Jun. 2023
A = [3000, 10^20, 10^14]
A has been assigned multiple values at the same time.
Siehe auch
Kategorien
Mehr zu Particle & Nuclear Physics finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!