1 / 6

MATLAB Examples

MATLAB Examples. Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr. MATLAB Examples. Find the number of positive numbers in a vector

penda
Télécharger la présentation

MATLAB Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATLAB Examples Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr

  2. MATLAB Examples • Find the number of positive numbers in a vector x = input( 'Enter a vector: ' );count = 0;for ii = 1:length(x), if ( x(ii) > 0 ), count = count + 1; endendfprintf('Number of positive numbers is %d\n', count); CS 111

  3. MATLAB Examples • Find the index of the largest number in a vector x = input( 'Enter a vector: ' );max_value = x(1);max_index = 1;for ii = 2:length(x), if ( x(ii) > max_value ), max_value = x(ii); max_index = ii; endendfprintf( 'Max value is %d\n', max_value );fprintf( 'Its index is %d\n', max_index ); • What if the max value occurs more than once? CS 111

  4. MATLAB Examples • Print a triangle of stars in n rows n = input( 'Enter the number of rows: ' );for ii = 1:n, for jj = 1:ii, fprintf( '*' ); end fprintf( '\n' );end CS 111

  5. MATLAB Examples • Find the kth digit of a number (kth digit from the right) num = input( 'Enter the number: ' );k = input( 'Enter the digit you want: ' );num_orig = num;for ii = 1:k, digit = mod( num, 10 ); num = fix( num / 10 );endfprintf('Digit %d of %d is %d\n', k, num_orig, digit); CS 111

  6. MATLAB Examples • Sort the numbers in a given vector x = input( 'Enter the vector to sort: ' );n = length(x);%length of the vector%Sort the vector in ascending order using selection sortfor ii = 1:n-1,%Find the minimum value in x(ii) through x(n) iptr = ii;for jj = ii+1:n,if ( x(jj) < x(iptr) ), iptr = jj;endend%iptr now points to the minimum value,%so swap x(iptr) with x(ii) if ii ~= iptrif ( ii ~= iptr ), temp = x(ii); x(ii) = x(iptr); x(iptr) = temp;endenddisp( 'Sorted vector:' );disp(x); CS 111

More Related