matlab中矩阵的logical函数,Matlab中的logical

Matlab中什么是logical

logical作为逻辑变量,可以是一种数据类型,第一次见到是在workspace里100*1logical,可以用在取出最值。

logical是布尔变量,可以是一个标量,也可以是一个向量或者是矩阵。可以用作下标。

在帮助文档中给出了一个例子:

A = [1 2 3; 4 5 6; 7 8 9]

要想取出对角元素,可以用diag(A),也可以借助下标。

构建一个logical矩阵,或者说是下标矩阵 logical(eye(3))

T=eye(3)是3*3单位阵

logical(T)是把为真(1)的值取出

即:eye(3)=[1 00; 0 10; 0 01;]

A(logical(eye(3))的意思是取出下标为真的元素:

最终返回:[1;5;9];

求极值

clear;

N = 100;

v = rand (N,1);

t = 0:length(v)-1;

Lmax = diff(sign(diff(v)))== -2; % logic vector for the local max

value

Lmin = diff(sign(diff(v)))== 2; % logic vector for the local min

value

% match the logic vector to the original vecor to have the same

length

Lmax = [false; Lmax; false];

Lmin = [false; Lmin; false];

tmax = t (Lmax); % locations of the local max elements

tmin = t (Lmin); % locations of the local min elements

vmax = v (Lmax); % values of the local max elements

vmin = v (Lmin); % values of the local min elements

% plot them on a figure

plot(t,v);

xlabel('t'); ylabel('v');

hold on;

plot(tmax, vmax, 'r+');

plot(tmin,vmin, 'g+');

hold off;