How to output WHOLE vector in result?

조회 수: 264(최근 30일)
Scott 2014년 10월 28일
편집: Andrew Reibold 2014년 10월 28일
I am trying to build a very simple function which just takes two values from a vector, and reverses their position. So if your inputted vector is [a,b], your output is [b,a].
I realized that there need be no commands in the actual function, we can just switch these values in the function statement itself. So here's what I've got:
function[second,first] = swap(first,second)
This seems to work, however it only outputs one of the values when it returns.
So if I type swap(11,4) It returns only 4, not the whole vector which would be [4,11]
Any thoughts?


Andrew Reibold
Andrew Reibold 2014년 10월 28일
편집: Andrew Reibold 2014년 10월 28일
You need to tell Matlab where to store both output arguments or it only gives the first one under the variable 'ans' by default
function [ b, a ] = swap(a, b)
Replicating what you did:
>> swap(4,11)
ans =
ans is only one variable, so only one output will go to it. If you want both outputs, tell Matlab what they should be saved under. Two outputs requires two variables.
Here is an example. Same code, but now I am calling it differently by putting [b,a] first. I am telling Matlab where it can store the outputs
>> [b,a] = swap(4,11)
b =
a =
If you want them to be concatenated into ONE output, it will require at least ONE line of code, or at least to my knowledge it will.
function [ c ] = swap(a, b)
c = [b, a]

James Tursa
James Tursa 2014년 10월 28일
편집: James Tursa 2014년 10월 28일
Your function, as written, takes two inputs and returns two outputs. You probably called your function with only one output which is why it discarded the second output. It sounds like you want the function to input a vector of 2 elements and return a vector of 2 elements that are swapped. If so, something like this maybe?
function y = swap(x)
y = (insert your element by element swapping code here)
  댓글 수: 2
Adam 2014년 10월 28일
It's not really a function if it doesn't have a body although in this case it would be a rare situation in which it would be the neatest way to swap two values.
The problem is you have 2 input arguments and two output arguments so you have to call the function as:
[y, x] = sort( x, y );
But your input is not an array in that case, just two scalars.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by