初学matlab,总结如下,希望对初学者有所帮助。
1初始化变量
var=40*i; //初始化var为复数0 +40.0000i
var2=var/5;
array=[1 2 3 4];
x=1;y=2;
2克隆运算符
它指定了这个系列数的第一值,步增和最后一个值
如x=1:2:10
x =1 3 5 7 9
f = [1:4]';
3 in1 = input('enter data:');
4画图
x = 0:1:10;
y = x.^2-10*x+15;
plot(x,y);
plot(x,y,'r--',x,y,'bo');
5一个图中画两个函数用hold on
x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'b-');
hold on;
plot(x,y2,'k--');
hold off;
legend ('sin x','cos x')
6分支结构
ax2+ bx + c = 0
matlab程序
% Prompt the user for the coefficients of the equation
disp ('This program solves for the roots of a quadratic ');
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: ');
% Calculate discriminant
discriminant = b^2 - 4 * a * c;
% Solve for the roots, depending on the vlaue of the discriminant.
if discriminant > 0 % there are two real roots, so ...
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
disp('This equation has two real roots:');
fprintf('x1 = %f\n', x1);
fprintf('x2 = %f\n', x2);
elseif discriminant == 0 % there is one repeated root, so ...
x1 = ( -b ) / (2*a);
disp('This equation has two identical real roots:');
fprintf('x1 = x2 = %f\n', x1);
else % there are complex roots, so ...
real_part = (-b) / (2*a);
imag_part = sqrt( abs(discriminant)) / (2*a);
disp('This equation has complex roots:');
fprintf('x1 = %f + i %f \n',real_part, imag_part);
fprintf('x2 = %f - i %f \n', real_part, imag_part);
end
7循环结构
n = 0; sum_x = 0; sum_x2 = 0;
% Read in first value
x = input('Enter first value: ');
% While Loop to read input values. 23
while x >= 0
% Accumulate sums. 25
n = n + 1;
sum_x = sum_x + x;
sum_x2 = sum_x2 + x^2;
% Read in next value 29
x = input('Enter next value: ');
end
% Calculate the mean and standard deviation 32
x_bar = sum_x / n;
std_dev = sqrt( (n * sum_x2 - sum_x^2) / (n * (n-1)) );
% Tell user. 35
fprintf('The mean of this data set is: %f\n', x_bar);
fprintf('The standard deviation is: %f\n', std_dev);
fprintf('The number of data points is: %f\n', n);
8稀疏矩阵
a = eye(10)
as = sparse(a)
as =(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
(6,6) 1
(7,7) 1
(8,8) 1
(9,9) 1
(10,10) 1
参考文献 MATLAB编程(中文第二版)