matlab cody study notes day4

(1) When I feel that using the find function to make good use of matlab's good matrix processing features, there is even a simpler way without finding.
For example, replace the numbers in the array x that are less than 0 and greater than 10 with Nan. Everyone generally uses a loop to judge x(i). I use find to find:
temp = find(x<0 |x>10);
x( temp) = Nan;
In fact, it can be simplified to:
x(x <0 | x> 10) = NaN;

(2) The last column/behavior end of the matrix does not need to know the specific number. It is very convenient to learn to use 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

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

(4) Determine that all elements of an array x are increasing.
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

Improvement:
tf = ~any(diff(x)<0)

Guess you like

Origin blog.csdn.net/yxnooo1/article/details/112600353