MATLAB程序设计-分支结构

分支结构
a = 20;
b = -2;
c = 0;
d = 1;
%if结构
if a<12
    a = a + 4;
elseif (a>12)&(a<24)
    a = a + 8;
else 
    a = a + 12;
end
%检验判别式
if (b^2 - 4*a*c)>0
    disp('this equation has two complex roots');
elseif (b^2 - 4*a*c)==0
    disp('this equation has two identical real roots')
else
    disp('Write msg that equation has two distinct real roots')
end

分支结构的应用
  • 求解二次方程的根
%求解二次方程的根
disp('equation of the form A*X^2 + B*X + C = 0');
a = input('Enter the coefficient A:');
b = input('Enter the coefficient B:');
c = input('Enter the coefficient C:');
disc = b^2 - 4*a*c;
if disc>0
    x1 = (-b - sqrt(disc))/(2*a);
    x2 = (-b + sqrt(disc))/(2*a);
    fprintf('x1= %f\n',x1);
    fprintf('x2=%f\n',x2);
elseif disc==0
    x = -b/(2*a);
    fprintf('x=%f\n',x);
else
    real_part = -b/(2*a);
    imag_part = sqrt(abs(disc))/(2*a);
    fprintf('x1=%f +i%f\n',real_part,imag_part);
    fprintf('x1=%f -i%f\n',real_part,imag_part);
end

  • 求解二元函数的解
%求解二元函数的解
disp('Enter the values');
x = input('Enter coggicient x:');
y = input('Enter coggicient y:');
if (x>=0)&(y>=0)
    f = x+y;
elseif (x>=0)&(y<0)
    f = x+y^2;
elseif (x<0)&(y>=0)
    f = x^2+y;
else
    f = x^2+y^2;
end
fprintf('f=%f\n',f);
    
switch语句
%switch结构
value = input('the value:');
switch(value)
    case{1,3,5,7,9}
        disp('the value is odd');
    case{2,4,6,8,10}
        disp('the value is even');
    otherwise
        disp('the value is out of range');
end

try/catch结构
%try/catch结构
try
    fprintf(values);
catch
    disp('上面的代码错了');
end

好的,我会尽力回答你关于 MATLAB 程序设计中的分支结构和循环结构的问题。 MATLAB 中的分支结构包括 if 语句和 switch 语句。if 语句用于根据指定的条件执行不同的代码块。例如,以下代码将根据变量 x 的值输出不同的消息: ``` matlab if x > 0 disp('x is positive'); elseif x < 0 disp('x is negative'); else disp('x is zero'); end ``` switch 语句用于根据变量的值执行不同的代码块。以下是一个计算几何图形面积的示例,其中根据用户选择的形状计算不同的面积: ``` matlab shape = input('Enter shape (circle, square, rectangle): ','s'); switch shape case 'circle' radius = input('Enter radius: '); area = pi * radius^2; case 'square' side = input('Enter side length: '); area = side^2; case 'rectangle' length = input('Enter length: '); width = input('Enter width: '); area = length * width; otherwise disp('Invalid shape'); end disp(['Area of ' shape ': ' num2str(area)]); ``` MATLAB 中的循环结构包括 for 循环和 while 循环。for 循环用于按指定次数执行代码块。例如,以下代码将计算从 1 到 10 的整数之和: ``` matlab sum = 0; for i = 1:10 sum = sum + i; end disp(['Sum of integers from 1 to 10: ' num2str(sum)]); ``` while 循环在指定条件为 true 时执行代码块。例如,以下代码将计算直到和超过 100 为止的整数之和: ``` matlab sum = 0; i = 1; while sum < 100 sum = sum + i; i = i + 1; end disp(['Sum of integers until sum >= 100: ' num2str(sum)]); ``` 以上就是 MATLAB 中的分支结构和循环结构的简单介绍,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值