Hi I need help with this problem in MATLAB CODE!

1 vue (au cours des 30 derniers jours)
Anthony Fuentes
Anthony Fuentes le 28 Nov 2016
Modifié(e) : bio lim le 28 Nov 2016
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 commentaires
Hildo
Hildo le 28 Nov 2016
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 le 28 Nov 2016
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.

Connectez-vous pour commenter.

Réponse acceptée

bio lim
bio lim le 28 Nov 2016
Modifié(e) : bio lim le 28 Nov 2016
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.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing 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