I need help writing a program to pick the largest number in a list

조회 수: 15 (최근 30일)
I was given:
clc;
n=input('how many numbers are in your list?');
for i=1:n
y=['enter a number', num2str(i)];
disp (y)
x(i)=input('');
end
and the list of numbers to plug in. I need to finish the program so it will choose the largest from my list. This is what I have so far:
if x(i)<=y
[newx,newy]=swap (x,y)
newx=y
newy=x
else x(i)>y
disp('The largest number in the list is')
end
This program runs but does not give me a single value. What should i do to fix it?
  댓글 수: 12
Walter Roberson
Walter Roberson 2017년 2월 13일
Computers cannot "just look", but they can use the same kind of procedure you describe.
justin simmons
justin simmons 2017년 2월 13일
How would I write a program to follow that procedure? And thank you for helping and teaching me as well.

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

채택된 답변

Seyedali Mirjalili
Seyedali Mirjalili 2017년 2월 12일
편집: Seyedali Mirjalili 2017년 2월 12일
Try this:
my_max = -inf;
for k=1:length(y) % y is your array
if my_max < y(k)
my_max = y(k);
end
end
disp(my_max)
This is computationally expensive though. You can find the maximum easily with the function max:
my_max = max(y'); %y is your array. If it is already a column vector, you do not need to transpose it
  댓글 수: 2
justin simmons
justin simmons 2017년 2월 12일
The largest number in my list is 52 but when I use the max function it says my largest number is 117.
Image Analyst
Image Analyst 2017년 2월 13일
Show your code and your data, or tell us what you entered.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by