Effacer les filtres
Effacer les filtres

Please HELP!! Am I nuts?

1 vue (au cours des 30 derniers jours)
Ali
Ali le 7 Nov 2012
I define a function and save it:
function [new_x, new_y] = TestArray(x, y)
new_y = y.^2;
new_x = x;
end
At cursor I type:
x = 1:10
y = 1:10:30
Answer = TestArray(x, y)
I get:
Answer =
1 2 3 4 5 6 7 8 9 10
How on earth is this possible? I am feeling tired but I can only assume I am going crazy, tiredness cannot be a reason for this level stupidity?! Shouldn't i return an matrix with size [2x10]?

Réponse acceptée

Image Analyst
Image Analyst le 7 Nov 2012
[new_x, new_y] in the function definition, or when you actually call this function, does not mean that you will get one variable out with new_x in column 1 and new_y in column 2, like you would if you did this:
c = [columnVector1 columnVector2];
It behaves differently. When calling or defining a function, it means that you get two variables returned and they are separate - not concatenated. If you specify only one, it will give you the left most return variable and any to the right of it are "thrown away" because you did not supply a variable in your calling routine to accept them. I hope that explains it.

Plus de réponses (2)

Friedrich
Friedrich le 7 Nov 2012
Modifié(e) : Friedrich le 7 Nov 2012
Hi,
this behavior is correct. In a function the output arguments aren't concatinated. They are returned as several outputs.
Try calling your function TestArray as
[Answer, Answer2] = TestArray(x, y)
If you want to have a 2x10 Matrix as output, then you need to concatinate it yourself inside the function.

Ali
Ali le 7 Nov 2012
Thanks! I am surprised I haven't run into this before.

Catégories

En savoir plus sur Variables 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!

Translated by