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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值