Jump to content

MATLAB question

nflasky

I had to write a program for my MATLAB class to sort a user given 5x5 matrix, and then sort this matrix by either rows or columns and give the CPU time.  I seem to have everything working out fine.  However, I am still trying to figure out how to prevent the user from entering a complex number or a string.  I know MATLAB has a built in isreal function that I may be able to use.  Just wondering if anybody could give me some advice.  My code is below:

 

for i = 1:5 
for j = 1:5 
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': ']; 
matrix(i,j) = input(str); 
end 
end 
choice = menu('Enter row or column','Row', 'Column');
switch choice
   case 1
      answer = sort(matrix, 2, 'ascend');
      disp('The sorted matrix by columns is: ')
      disp(answer)
      disp('The original matrix is: ')
      disp(matrix)
   case 2 
      disp('The sorted matrix by rows is: ')
      sort(matrix)
      disp('The original matrix is: ')
      disp(matrix)
 end
      cpu = cputime;
      disp('Your CPU time is: ') 
      disp(cputime)
      
Link to comment
Share on other sites

Link to post
Share on other sites

The ideal spot to check would be using the isreal function as a conditional before assigning the value to matrix(i,j)

 

if (isreal(inputval))> assign valueelse > prompt to re-enter valueend

 

Or something along those lines. You may need to throw the above conditional inside a while (true) loop (to keep the loop going for as long as a complex number is being entered), as well as a break statement after assigning matrix(i,j) = input(str)

Interested in Linux, SteamOS and Open-source applications? Go here

Gaming Rig - CPU: i5 3570k @ Stock | GPU: EVGA Geforce 560Ti 448 Core Classified Ultra | RAM: Mushkin Enhanced Blackline 8GB DDR3 1600 | SSD: Crucial M4 128GB | HDD: 3TB Seagate Barracuda, 1TB WD Caviar Black, 1TB Seagate Barracuda | Case: Antec Lanboy Air | KB: Corsair Vengeance K70 Cherry MX Blue | Mouse: Corsair Vengeance M95 | Headset: Steelseries Siberia V2

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×