Hi; Can you help me to find fault in my code?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Write a function called sort3 that takes a 3-element vector as its sole arguments. It uses if-statements, possibly nested, to return the three elements of the vector as three scalar output arguments in nondecreasing order, i.e., the first output argument equals the smallest element of the input vector and the last output argument equals the largest element. NOTE: Your function may not use any built-in functions, e.g., sort, min, max, median, etc.
My code;
function [s1 s2 s3] = sort3(V)
a = V(1), b = V(2), c = V(3);
if a<=b && a<=c
s1 = a;
if b<=c
s2 = b;
s3 = c;
else
s2=c;
s3=b;
end
else if b<=a && b<=c
s1=b;
if a<=c
s2=a;
s3=c;
else
s2=c;
s3=a;
end
else c<=b && c<=a
s1=c;
if b<=a
s2=b;
s3=a;
else
s2=a;
s3=b;
end
end
The fault;
>> [s1 s2 s3] = sort3([4 18 3])
Error: File: sort3.m Line: 3 Column: 5
At least one END is missing: the statement may begin here.
I dont understand this fault.
1 Kommentar
Antworten (4)
Walter Roberson
am 31 Okt. 2017
Count nesting:
function [s1 s2 s3] = sort3(V)
a = V(1), b = V(2), c = V(3);
if a<=b && a<=c %enter nesting 1
s1 = a;
if b<=c %enter nesting 2
s2 = b;
s3 = c;
else %continue nesting 2
s2=c;
s3=b;
end %end nesting 2, resume nesting 1
else if b<=a && b<=c %continue nesting 1 with "else", enter nesting 2 with "if"
s1=b;
if a<=c %enter nesting 3
s2=a;
s3=c;
else %continue nesting 3
s2=c;
s3=a;
end %end nesting 3, resume nesting 2
else c<=b && c<=a %continue nesting 2 with "else". Print out the result of "c<=b && c<=a" because there is no "if" statement here
s1=c;
if b<=a %enter nesting 3
s2=b;
s3=a;
else %continue nesting 3
s2=a;
s3=b;
end %end nesting 3, resume nesting 2
end %end nesting 2, resume nesting 1
%uh-oh, we are at end of routine and still in nesting 1!
Please review "else if" compared to "else if"
0 Kommentare
Vignesh M
am 4 Mai 2018
Bearbeitet: Walter Roberson
am 4 Mai 2018
function [u1,u2,u3] = sort3(v)
if v(1) <= v(2) && v(2) <= v(3);
u1=v(1);u2=v(2);u3=v(3);
elseif v(1) <= v(3) && v(3) <= v(2);
u1=v(1);u2=v(3);u3=v(2);
elseif v(2) <= v(1) && v(1) <= v(3);
u1=v(2);u2=v(1);u3=v(3);
elseif v(2) <= v(3) && v(3) <= v(1);
u1=v(2);u2=v(3);u3=v(1);
elseif v(3) <= v(1) && v(1) <= v(2);
u1=v(3);u2=v(1);u3=v(2);
else v(3) <= v(2) && v(2) <= v(1);
u1=v(3);u2=v(2);u3=v(1);
end
end
0 Kommentare
Dong Chen
am 11 Jun. 2018
Bearbeitet: Walter Roberson
am 12 Jun. 2018
function [x y z] = sort3(m)
x = m(1);
y = m(2);
z = m(3);
if (x>y)
t = x;
x = y;
y = t;
end
if (x>z)
t = z;
z = x;
x = t;
end
if (y>z)
t = y;
y = z;
z = t;
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Elementary Math finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!