matlab cody学习笔记 day4

(1)在我感慨活用find函数能把matlab善于矩阵处理的特性好好发挥的时候,竟然有更简单不用find的方式。
例如将数组x里小于0,大于10的数替换为Nan,大家一般都用循环在对x(i)进行判断,我用find寻找:
temp = find(x<0 |x>10);
x(temp) = Nan;
其实,完全可以简化为:
x(x < 0 | x > 10) = NaN;

(2)矩阵的最后一列/行为end,可以不用知道具体数。学会用end很方便。

(3)构造棋盘矩阵
Given an integer n, make an n-by-n matrix made up of alternating ones and zeros as shown below. The a(1,1) should be 1.
Example:
Input n = 5
Output a is [1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1]

原循环程序:
board = zeros(n,n);
for j = 1:n
if mod(j,2)==0 %if zero row is even
for i =1:2:n
board(j,i) = 1;
end
else mod(j,2)==1 %if 1, row is odd
for t = 2:2:n
board(j,t) = 1;
end
end
end
end

改进:
a = ones(n);
a(2:2:n,1:2:n) = 0;
a(1:2:n,2:2:n) = 0;

(4)判断一个数组x的所有元素都是递增的。
Examples:
Input x = [-3 0 7]
Output tf is true
Input x = [2 2]
Output tf is false

原循环代码:
for i:1:(length(x)-1)
if x(i+1) > x(i)
tf = “true”
else
tf= “false”
end
end
end

改进:
tf = ~any(diff(x)<0)

猜你喜欢

转载自blog.csdn.net/yxnooo1/article/details/112600353