1.sort() 排序,默认升序(从小到大)
vec=[12 78 10 6 98]
sort(vec)
ans =
6 10 12 78 98
升序参数:
sort(vec,'ascend')
ans =
6 10 12 78 98
降序参数:
sort(vec,'descend')
ans =
98 78 12 10 6
2.利用sort获取struct中某参数大小排序及序号排序,
以便利用序号取用按该参数排序的其它参数。
pack(1)=struct('code','c','dimension',struct('hsaj',1),'weight',2)
pack(2)=struct('code','o','dimension',struct('hsaj',5),'weight',6)
pack(3)=struct('code','j','dimension',struct('hsaj',-5),'weight',5)
样例1(struct数组):
[w_sorted,i_sorted]=sort([pack.weight])
w_sorted =
2 5 6
i_sorted =
1 3 2
按weight大小输出code:
pack([i_sorted]).code
ans =
'c'
ans =
'j'
ans =
'o'
若不需要获得某个返回,则用~代替:
[~,i_sorted]=sort([pack.weight])
i_sorted =
1 3 2
样例2(table数组):
names={'Harry','Sally','Jose'};
heights=[185;133;210];
weight=[74;65.4;72.2];
paients=table(weight,heights,'RowNames',names)
paients =
weight heights
______ _______
Harry 74 185
Sally 65.4 133
Jose 72.2 210
按weight从小到大取用:
[~,i_order]=sort(paients{:,'weight'})
i_order =
2
3
1
paients(i_order,:)
weight heights
______ _______
Sally 65.4 133
Jose 72.2 210
Harry 74 185
3.issortedrows(),判断某元素集合是否按某一元素大小排序
issortedrows(paients,'weight')
ans =
logical
1
4. nargin 系统自动计数输入变量个数
5.function [a b]=area(varargin) varargin 作为形式变量,解读方式不同
6. function varargout=example(x,varargin)
7. function 在if里面,因为end会混淆
8. 外部函数的变量可以被内部函数使用,反之则不成立
9.内部函数对外部函数传入的变量做出的改变只在内部函数里面有效;
内部函数对外部函数定义的变量做出的改变在外部也有效;
内部函数只有被外部函数引用时才起作用。
例如:
function out=jk(a,b)
out=a*b;
m=1;
fprintf("out: %d a: %d b:%d m:%d\n ",out,a,b,m);
function iner=op(a,b)
a=a+1;
b=b+1;
m=m+6;
iner=a*b;
fprintf("iner: %d a: %d b:%d m: %d\n",iner,a,b,m);
end
op(a,b);
a=a+50;
b=b+50;
fprintf("out: %d a: %d b:%d m:%d\n ",out,a,b,m);
end
输出:
jk(4,5)
out: 20 a: 4 b:5 m:1
iner: 30 a: 5 b:6 m: 7
out: 20 a: 54 b:55 m:7
ans =
20
10. 一行写函数:
function area= calcarea(rad)
area=pi * rad.^2;
fprintf('the answer is %f , it`s rad is %f\n',area ,rad);
end
变为:
cirarea2=@(rad)pi*rad.^2;
使用:
cirarea2(1);
10. 返回的数据合成一个向量(数组)
vol=@(len,wid,ht)[len*wid*ht,len*wid];
>> vol(1,2,3)
ans =
6 2
11.不需要输入变量的函数,需要带上();
prtrand=@()fprintf('%.2f\n',rand)
prtrand =
包含以下值的 function_handle:
@()fprintf('%.2f\n',rand)
>> prtrand()
0.81
12.保存匿名函数save:
save 'prtrand' 'prtrand'
>> prtrand()
0.91
>> load prtrand.mat
13. factorial(Num):返回阶层
14.给函数一个别名,使之可以被引用,从而用作变量
fact=@factorial;
15.把函数,函数句柄作为参数传入:
function fnfmap(funh)
x=1:0.25:6;
y=funh(x);
plot(x,y,'ko');
end
函数:
>> fnfmap(@sin)
函数句柄:
>> fn=@sin;
>> fnfmap(fn)
fnfmap(@(x)x.^2+cos(x))
16. func2str() 返回函数句柄对应的函数
17.timeit() 计算执行函数的时间,传入参数为函数句柄
fun=@()sum(1:1E6)
一,
timeit(fun)
ans =
0.0014
二,
tic;timeit(fun);toc;
历时 0.002249 秒。
由于时间短,tic,toc不够精确
16. 函数递归
function ans=jiec(x)
t=1;
if x==1
ans=1;
else
ans=x*jiec(x-1)
end
end
17. prod() 连乘
18.strtok() 截断字符串并返回第一个
strp="i kj po"
strp =
"i kj po"
>> strtok(strp)
ans =
"i"
19. 数据结构的一些建议:
1.每一行每一列为单独矩阵,后存入cell