inputs of multi-variable functions?

27 visualizaciones (últimos 30 días)
Abdelrahman Taha
Abdelrahman Taha el 11 de En. de 2020
Comentada: Abdelrahman Taha el 11 de En. de 2020
I was wondering about how matlab deals with multiple inputs in a multivariable function. And I mean by that the order in which it assigns the predefined parameters to the inputs of the function in case they're given different symbols from those of the function's inputs.
For example, I've created a fun that substracts one num from another as following:
function c=sub(a,b)
c=a-b;
end
When I give it those inputs (e=3; f=2), i get -1, while doing the reverse (e=2; f=3) gives me the same ans as well! So, I can't detect a certain pattern in which matlab deals with this. And of course that doesn't happen when i give the parameter the same symbols of the function's inputs.

Respuesta aceptada

Stephen23
Stephen23 el 11 de En. de 2020
"Is there a right order for input variables in a function?"
Yes: MATLAB function inputs are positional:
The 1st input provided is the 1st input argument inside the function.
The 2nd input provided is the 2nd input argument inside the function.
etc.
The names of any variables that might be used when calling a function are (and should be) totally irrelevant. Beginners sometimes like to use the same names inside a function and also for the names of variables when they call that function, but often this just adds to their confusion as they think that those two independent sets of names should "match up" somehow, regardless of the order they provide them in. They don't: all input arguments are determined by their position.
"How do I make the function see the input variables correctly as it is in the main program?"
You provide the input data in the correct order, based on the specification of that function. For example:
function Z = mysub(A,B)
Z = A - B;
end
This will subtract the second input argument from the first input argument (regardless of any possible variable names that might be used when calling the function):
>> A = 10;
>> B = 4;
>> mysub(A,B)
ans = 6
>> B = 10;
>> A = 4;
>> mysub(B,A)
ans = 6
I strongly recommend that you do NOT write your code assuming that the calling variable names are anything like the ones used inside the function.

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by