Hi I need help with this problem in MATLAB CODE!

1 回表示 (過去 30 日間)
Anthony Fuentes
Anthony Fuentes 2016 年 11 月 28 日
編集済み: bio lim 2016 年 11 月 28 日
Hi! I have a problem! I don't know how to do this in MATLAB CODE: Write a function in Matlab that receives a vector and determine if the numbers within the vector are ordered from least to greatest. The output must be a single variable that takes a value of 1 when the numbers are ordered or 0 (zero) otherwise.Write 2 versions of the function. One using "loops" and the other using vector operations (not "loops").Thanks a lot!
  2 件のコメント
Hildo
Hildo 2016 年 11 月 28 日
This appear to be a simple already solved problem. If I understand right you just have to use the function
issorted(X)
If you need to test the opposite order use
issorted(X(end:-1:1))
Steven Lord
Steven Lord 2016 年 11 月 28 日
If as I suspect this is homework and you are not allowed to use the issorted or sort functions, show what you've done to try to solve the problem and describe where you're having difficulty and we may be able to offer some guidance.

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

採用された回答

bio lim
bio lim 2016 年 11 月 28 日
編集済み: bio lim 2016 年 11 月 28 日
Loop version:
function Y = coffee(X)
Y = zeros(length(X)-1,1);
for i=1:(length(X)-1)
if X(i+1) >= X(i)
Y(i) = 1;
else Y(i) = 0;
end
end
if Y == 1
Y = 1;
else Y = 0;
end
end
Test:
vec = [1 7 6 2 8 9 10];
vec2 = [1 2 3 4 5];
vec = coffee(vec);
vec2 = coffee(vec2);
The output is:
vec =
0
vec2 =
1
Non-loop version: (As Hildo suggested)
function Y = coffee(X)
if issorted(X)
Y = 1;
else Y = 0;
end
And the output is the same. Moreover, as Steven Lord suggested, I doubt you are allowed to use issorted or sort function if this is a homework. I leave that part up to you since you have the basic idea now.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by