0 MATLAB的基本语法测试(7.20)
1冒泡排序
bubble_sort.m
function y=bubble_sort(x)
x_len=length(x);
for i=1:x_len-1
for j=1:x_len-i
if (x(j)>x(j+1))
[x(j),x(j+1)]=swap(x(j),x(j+1));
end
end
disp([num2str(i),'.Sort:x=',num2str(x)]);
end
y=x;
end
function [a,b]=swap(x,y)
a=y;
b=x;
end
test.m
clc;
clear;
X=randperm(6);
disp(['Before Sort:X=',num2str(X)]);
disp('--------------------');
y=bubble_sort(X);
disp(['Bubble Sort:x=',num2str(y)]);
2找矩阵的最大值
myfindmax.m
function [x,y] = myfindmax(A)
tem=max(A(:,:));%求每一列的最大值(不知道为什么)
res = max(tem) %求得最大值
[x,y] = find(A==res) %i,j分别代表行和列坐标
test.m
M = fix(100*rand(4,5))% 随机生成1–100的4X5的整数矩阵
myfindmax(M)
3.求阶乘和
(输入20)
JieCheng.m
function[sum] = JieCheng(n)
sum = 1
for i = 1:n
sum = sum*i
end
test.m
n = input('请输入n\n');
res = 0
for i = 1:n
res = res + JieCheng(i)
end
4.一 球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下.求它在第10次落地时,共经过多少米?第10次反弹有多高?
H =100
n = 10
sum = 0
for i = 1:10
if(i == 1)
sum = sum + H
else
sum = sum + H*2
end
H = H /2
end
5.求函数的值
F.m
functon [res] = F(x,y)
res = x^2+sin(x*y)+2*y
test.m
X = input('请输入X\n');
Y = input('请输入Y\n');
disp(['RES = ',num2str(F(X,Y))])