How to output WHOLE vector in result?

160 ビュー (過去 30 日間)
Scott
Scott 2014 年 10 月 28 日
コメント済み: Steven Lord 2022 年 9 月 27 日
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?

回答 (2 件)

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
Code:
function [ b, a ] = swap(a, b)
end
Replicating what you did:
>> swap(4,11)
ans =
11
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 =
11
a =
4
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]
end

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)
end
  4 件のコメント
Ranjith K
Ranjith K 2022 年 9 月 27 日
this is initial sequence {3 10 7 9 5 4 1 8 2 6}
how to change each value from beging of the initial sequence
for example initial sequence {3 10 7 9 5 4 1 8 2 6}
1. {10 3 7 9 5 4 1 8 2 6}
2.(7 3 10 7 9 5 4 1 8 2 6}
3. {9 3 10 9 5 4 1 8 2 6}
4. {5 3 10 7 9 4 1 8 2 6}
5. {4 3 10 7 9 5 1 8 2 6}
6. {1 3 10 7 9 5 4 8 2 6}
7.{8 3 10 7 9 5 4 1 2 6}
8. {2 3 10 7 9 5 4 1 8 6}
9. {6 3 10 7 9 5 4 1 8 2 }
Steven Lord
Steven Lord 2022 年 9 月 27 日
@Ranjith K Since this question doesn't seem to be closely related to the original question from 2014 I recommend you post it as its own question. Use the Ask link at the top of the page.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by