我是MATLAB的初学者,所以对此有一个疑问。我应该怎么写这段代码,如果有机会,有人可以友好地写出代码,因为我一直在努力。使用循环创建3 x 5矩阵,其中每个元素的值是其行号的一半加其列号的三倍。例如,元素(2,5)的值为:1/2 2 + 3 5
答案 0 :(得分:0)
嵌套循环控制矩阵的索引。外部for循环遍历矩阵的行,内部for循环遍历矩阵的列。
这个问题的第二部分要求结合使用循环/扫描变量Row
和Column
来设置矩阵的值:
矩阵值=(行÷2)+(3×列)
Number_Of_Rows = 3;
Number_Of_Columns = 5;
Matrix = zeros(Number_Of_Rows,Number_Of_Columns);
%Running through the array indices using two loops%
for Row = 1: Number_Of_Rows
for Column = 1: Number_Of_Columns
%Evaluating the value based on the current row and column index%
Matrix(Row,Column) = (Row/2) + (3*Column);
end
end
Matrix
答案 1 :(得分:0)
这是一种直观的方法:
% Initialize row num and column num
row = 3;
column = 5;
% H is the matrix of desire
% Initialize it as a 3*5 zero matrix
H = zeros(3,5);
% Outer loop, over column index
% Remember Matlab's index start with 1 not 0
for c = 1:column
% Inner Loop, over row index
for r = 1:row
% The algorithm of each element in the matrix
H(r,c) = 0.5*r+3*c;
end
end