nrows = 4; ncols = 6; A = ones(nrows,ncols);
遍历矩阵并为每个元素指定一个新值。对主对角线赋值 2
,对相邻对角线赋值 -1
,对其他位置赋值 0
。
for c = 1:ncols for r = 1:nrows if r == c A(r,c) = 2; elseif abs(r-c) == 1 A(r,c) = -1; else A(r,c) = 0; end end end A
A = 4×6
2 -1 0 0 0 0
-1 2 -1 0 0 0
0 -1 2 -1 0 0
0 0 -1 2 -1 0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
确定值是否在指定范围内。
x = 10; minVal = 2; maxVal = 6; if (x >= minVal) && (x <= maxVal) disp('Value within specified range.') elseif (x > maxVal) disp('Value exceeds maximum value.') else disp('Value is below minimum value.') end
Value exceeds maximum value.