How to create a function that can accommodate multiple definitions of the same variable?
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Walter Roberson
le 4 Mar 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
le 13 Mar 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!
Réponses (1)
Shree Harsha Kodi
le 17 Juin 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 commentaire
Walter Roberson
le 17 Juin 2023
A = [3000, 10^20, 10^14]
A has been assigned multiple values at the same time.
Voir également
Catégories
En savoir plus sur Particle & Nuclear Physics dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!