楼主: Lisrelchen
1017 6

[Matlab-Based Book]MATLAB程式設計與應用(第三版) [推广有奖]

  • 0关注
  • 62粉丝

VIP

已卖:4192份资源

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50278 个
通用积分
83.5106
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

楼主
Lisrelchen 发表于 2016-3-21 06:09:04 |AI写论文
1论坛币

本书将 MATLAB 作为一种技术编程语言进行介绍,并且向学生展示如何编写效率高、组织严谨的程序,同时强调问题解决技巧。书中重点介绍良好的编程实践、MATLAB 编程中的常见错误,以及大量使用 MATLAB 科学计算软件解决的练习和示例。

关键词:MATLAB atlab matla Based Base 编程语言 程序 技巧 技术 如何

沙发
Lisrelchen 发表于 2016-3-21 06:10:01
  1. %  Script file: calc_roots.m
  2. %
  3. %  Purpose:
  4. %    This program solves for the roots of a quadratic equation
  5. %    of the form a*x**2 + b*x + c = 0.  It calculates the answers
  6. %    regardless of the type of roots that the equation possesses.
  7. %
  8. %  Record of revisions:
  9. %      Date       Programmer          Description of change
  10. %      ====       ==========          =====================
  11. %    01/12/07    S. J. Chapman        Original code
  12. %
  13. % Define variables:
  14. %   a            -- Coefficient of x^2 term of equation
  15. %   b            -- Coefficient of x term of equation
  16. %   c            -- Constant term of equation
  17. %   discriminant -- Discriminant of the equation
  18. %   imag_part    -- Imag part of equation (for complex roots)
  19. %   real_part    -- Real part of equation (for complex roots)
  20. %   x1           -- First solution of equation (for real roots)
  21. %   x2           -- Second solution of equation (for real roots)

  22. % Prompt the user for the coefficients of the equation
  23. disp ('This program solves for the roots of a quadratic ');
  24. disp ('equation of the form A*X^2 + B*X + C = 0. ');
  25. a = input ('Enter the coefficient A: ');
  26. b = input ('Enter the coefficient B: ');
  27. c = input ('Enter the coefficient C: ');

  28. % Calculate discriminant
  29. discriminant = b^2 - 4 * a * c;

  30. % Solve for the roots, depending on the value of the discriminant
  31. if discriminant > 0 % there are two real roots, so...

  32.    x1 = ( -b + sqrt(discriminant) ) / ( 2 * a );
  33.    x2 = ( -b - sqrt(discriminant) ) / ( 2 * a );
  34.    disp ('This equation has two real roots:');
  35.    fprintf ('x1 = %f\n', x1);
  36.    fprintf ('x2 = %f\n', x2);

  37. elseif discriminant == 0  % there is one repeated root, so...

  38.    x1 = ( -b ) / ( 2 * a );
  39.    disp ('This equation has two identical real roots:');
  40.    fprintf ('x1 = x2 = %f\n', x1);

  41. else % there are complex roots, so ...

  42.    real_part = ( -b ) / ( 2 * a );
  43.    imag_part = sqrt ( abs ( discriminant ) ) / ( 2 * a );
  44.    disp ('This equation has complex roots:');
  45.    fprintf('x1 = %f +i %f\n', real_part, imag_part );
  46.    fprintf('x1 = %f -i %f\n', real_part, imag_part );

  47. end
复制代码

藤椅
Lisrelchen 发表于 2016-3-21 06:10:58
  1. %  Script file: funxy.m
  2. %
  3. %  Purpose:
  4. %    This program solves the function f(x,y) for a
  5. %    user-specified x and y, where f(x,y) is defined as:
  6. %                 _
  7. %                |
  8. %                | x + y             x >= 0 and y >= 0
  9. %                | x + y^2           x >= 0 and y < 0
  10. %       f(x,y) = | x^2 + y           x < 0  and y >= 0
  11. %                | x^2 + y^2         x < 0  and y < 0
  12. %                |_
  13. %
  14. %  Record of revisions:
  15. %      Date       Programmer          Description of change
  16. %      ====       ==========          =====================
  17. %    01/13/07    S. J. Chapman        Original code
  18. %
  19. % Define variables:
  20. %   x     -- First independent variable
  21. %   y     -- Second independent variable
  22. %   fun   -- Resulting function

  23. % Prompt the user for the values x and y
  24. x = input ('Enter the x coefficient: ');
  25. y = input ('Enter the y coefficient: ');

  26. % Calculate the function f(x,y) based upon
  27. % the signs of x and y.
  28. if x >= 0 && y >= 0
  29.    fun = x + y;
  30. elseif x >= 0 && y < 0
  31.    fun = x + y^2;
  32. elseif x < 0 && y >= 0
  33.    fun = x^2 + y;
  34. else
  35.    fun = x^2 + y^2;
  36. end

  37. % Write the value of the function.
  38. disp (['The value of the function is ' num2str(fun)]);
复制代码

板凳
Lisrelchen 发表于 2016-3-21 06:15:19
  1. %  Script file: ideal_gas.m
  2. %
  3. %  Purpose:
  4. %    This program plots the pressure versus volume of an
  5. %    ideal gas.
  6. %
  7. %  Record of revisions:
  8. %      Date       Programmer          Description of change
  9. %      ====       ==========          =====================
  10. %    01/16/07    S. J. Chapman        Original code
  11. %
  12. % Define variables:
  13. %   n         -- Number of atoms (mol)
  14. %   P         -- Pressure (kPa)
  15. %   R         -- Ideal gas constant (L kPa/mol K)
  16. %   T         -- Temperature (K)
  17. %   V         -- volume (L)

  18. % Initialize nRT
  19. n = 1;                   % Moles of atoms
  20. R = 8.314;               % Ideal gas constant
  21. T = 273;                 % Temperature (K)

  22. % Create array of input pressures.  Note that this
  23. % array must be quite dense to catch the major
  24. % changes in volume at low pressures.
  25. P = 1:0.1:1000;

  26. % Calculate volumes
  27. V = (n * R * T) ./ P;

  28. % Create first plot
  29. figure(1);
  30. loglog( P, V, 'r-', 'LineWidth', 2 );
  31. title('\bfVolume vs Pressure in an Ideal Gas');
  32. xlabel('\bfPressure (kPa)');
  33. ylabel('\bfVolume (L)');
  34. grid on;
  35. hold on;

  36. % Now increase temperature
  37. T = 373;                 % Temperature (K)

  38. % Calculate volumes
  39. V = (n * R * T) ./ P;

  40. % Add second line to plot
  41. figure(1);
  42. loglog( P, V, 'b--', 'LineWidth', 2 );
  43. hold off;

  44. % Add legend
  45. legend('T = 273 K','T = 373 K');
复制代码

报纸
Lisrelchen 发表于 2016-3-21 06:17:36
  1. %  Script file: ball.m
  2. %
  3. %  Purpose:
  4. %    This program calculates the distance traveled by a ball
  5. %    thrown at a specified angle "theta" and a specified
  6. %    velocity "vo" from a point on the surface of the Earth,
  7. %    ignoring air friction and the Earth's curvature.  It
  8. %    calculates the angle yielding maximum range, and also
  9. %    plots selected trajectories.
  10. %
  11. %  Record of revisions:
  12. %      Date       Programmer          Description of change
  13. %      ====       ==========          =====================
  14. %    01/30/07    S. J. Chapman        Original code
  15. %
  16. % Define variables:
  17. %   conv         -- Degrees to radians conv factor
  18. %   gravity      -- Accel. due to gravity (m/s^2)
  19. %   ii, jj       -- Loop index
  20. %   index        -- Location of maximum range in array
  21. %   maxangle     -- Angle that gives maximum range (deg)
  22. %   maxrange     -- Maximum range (m)
  23. %   range        -- Range for a particular angle (m)
  24. %   time         -- Time (s)
  25. %   theta        -- Initial angle (deg)
  26. %   traj_time    -- Total trajectory time (s)
  27. %   vo           -- Initial velocity (m/s)
  28. %   vxo          -- X-component of initial velocity (m/s)
  29. %   vyo          -- Y-component of initial velocity (m/s)
  30. %   x            -- X-position of ball (m)
  31. %   y            -- Y-position of ball (m)

  32. %  Constants
  33. conv = pi / 180;      % Degrees-to-radians conversion factor
  34. g = -9.81;            % Accel. due to gravity
  35. vo = 20;              % Initial velocity

  36. %Create an array to hold ranges
  37. range = zeros(1,91);

  38. % Calculate maximum ranges
  39. for ii = 1:91
  40.    theta = ii - 1;
  41.    vxo = vo * cos(theta*conv);
  42.    vyo = vo * sin(theta*conv);
  43.    max_time = -2 * vyo / g;
  44.    range(ii) = vxo * max_time;
  45. end

  46. % Write out table of ranges
  47. fprintf ('Range versus angle theta:\n');
  48. for ii = 1:91
  49.    theta = ii - 1;
  50.    fprintf('  %2d    %8.4f\n',theta, range(ii));
  51. end

  52. % Calculate the maximum range and angle
  53. [maxrange index] = max(range);
  54. maxangle = index - 1;
  55. fprintf ('\nMax range is %8.4f at %2d degrees.\n',...
  56.          maxrange, maxangle);

  57. % Now plot the trajectories
  58. for ii = 5:10:85

  59.    % Get velocities and max time for this angle
  60.    theta = ii;
  61.    vxo = vo * cos(theta*conv);
  62.    vyo = vo * sin(theta*conv);
  63.    max_time = -2 * vyo / g;

  64.    % Calculate the (x,y) positions
  65.    x = zeros(1,21);
  66.    y = zeros(1,21);
  67.    for jj = 1:21
  68.       time = (jj-1) * max_time/20;
  69.       x(jj) = vxo * time;
  70.       y(jj) = vyo * time + 0.5 * g * time^2;
  71.    end
  72.    plot(x,y,'b');
  73.    if ii == 5
  74.       hold on;
  75.    end
  76. end

  77. % Add titles and axis lables
  78. title ('\bfTrajectory of Ball vs Initial Angle \theta');
  79. xlabel ('\bf\itx \rm\bf(meters)');
  80. ylabel ('\bf\ity \rm\bf(meters)');
  81. axis ([0 45 0 25]);
  82. grid on;

  83. % Now plot the max range trajectory
  84. vxo = vo * cos(maxangle*conv);
  85. vyo = vo * sin(maxangle*conv);
  86. max_time = -2 * vyo / g;

  87. % Calculate the (x,y) positions
  88. x = zeros(1,21);
  89. y = zeros(1,21);
  90. for jj = 1:21
  91.    time = (jj-1) * max_time/20;
  92.    x(jj) = vxo * time;
  93.    y(jj) = vyo * time + 0.5 * g * time^2;
  94. end
  95. plot(x,y,'r','LineWidth',3.0);
  96. hold off
复制代码

地板
Lisrelchen 发表于 2016-3-21 06:18:44
  1. %  Script file: doy.m
  2. %
  3. %  Purpose:
  4. %    This program calculates the day of year corresponding
  5. %    to a specified date.  It illustrates the use switch
  6. %    and for constructs.
  7. %
  8. %  Record of revisions:
  9. %      Date       Programmer          Description of change
  10. %      ====       ==========          =====================
  11. %    01/27/07    S. J. Chapman        Original code
  12. %
  13. % Define variables:
  14. %   day          -- Day (dd)
  15. %   day_of_year  -- Day of year
  16. %   ii           -- Loop index
  17. %   leap_day     -- Extra day for leap year
  18. %   month        -- Month (mm)
  19. %   year         -- Year (yyyy)

  20. % Get day, month, and year to convert
  21. disp('This program calculates the day of year given the ');
  22. disp('specified date.');
  23. month = input('Enter specified month (1-12): ');
  24. day   = input('Enter specified day(1-31):    ');
  25. year  = input('Enter specified year(yyyy):   ');

  26. % Check for leap year, and add extra day if necessary
  27. if mod(year,400) == 0
  28.    leap_day = 1;          % Years divisible by 400 are leap years
  29. elseif mod(year,100) == 0
  30.    leap_day = 0;          % Other centuries are not leap years
  31. elseif mod(year,4) == 0
  32.    leap_day = 1;          % Otherwise every 4th year is a leap year
  33. else
  34.    leap_day = 0;          % Other years are not leap years
  35. end

  36. % Calculate day of year by adding current day to the
  37. % days in previous months.
  38. day_of_year = day;
  39. for ii = 1:month-1

  40.    % Add days in months from January to last month
  41.    switch (ii)
  42.    case {1,3,5,7,8,10,12},
  43.       day_of_year = day_of_year + 31;
  44.    case {4,6,9,11},
  45.       day_of_year = day_of_year + 30;
  46.    case 2,
  47.       day_of_year = day_of_year + 28 + leap_day;
  48.    end

  49. end

  50. % Tell user
  51. fprintf('The date %2d/%2d/%4d is day of year %d.\n', ...
  52.          month, day, year, day_of_year);
复制代码

7
Lisrelchen 发表于 2016-3-21 06:19:54
  1. %  Script file: logical1.m
  2. %
  3. %  Purpose:
  4. %    This program calculates the time required to
  5. %    calculate the square roots of all elements in
  6. %    array a whose value exceeds 5000.  This is done
  7. %    in two different ways:
  8. %    1.  Using a for loop and if construct.
  9. %    2.  Using a logical array.
  10. %
  11. %  Record of revisions:
  12. %      Date       Programmer          Description of change
  13. %      ====       ==========          =====================
  14. %    01/27/07    S. J. Chapman        Original code
  15. %
  16. % Define variables:
  17. %   a            -- Array of input values
  18. %   b            -- Logical array to serve as a mask
  19. %   ii, jj       -- Loop index
  20. %   average1     -- Average time for calculation 1
  21. %   average2     -- Average time for calculation 2
  22. %   maxcount     -- Number of times to loop calculation
  23. %   month        -- Month (mm)
  24. %   year         -- Year (yyyy)


  25. % Perform calculation using loops and branches.
  26. maxcount = 10;              % Number of repetitions
  27. tic;                        % Start timer
  28. for jj = 1:maxcount        
  29.    a = 1:10000;             % Declare array a
  30.    for ii = 1:10000   
  31.       if a(ii) > 5000
  32.          a(ii) = sqrt(a(ii));
  33.       end
  34.    end
  35. end
  36. average1 = (toc)/maxcount;  % Calculate average time


  37. % Perform calculation using logical arrays.
  38. maxcount = 100;             % Number of repetitions
  39. tic;                        % Start timer
  40. for jj = 1:maxcount        
  41.    a = 1:10000;             % Declare array a
  42.    b = a > 5000;            % Create mask
  43.    a(b) = sqrt(a(b));       % Take square root
  44. end
  45. average2 = (toc)/maxcount;  % Calculate average time

  46. % Display results
  47. fprintf('Loop / if approach =     %8.4f\n', average1);
  48. fprintf('Logical array approach = %8.4f\n', average2);
  49.          
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-12 05:51