有没有一种方法可以使用“ for循环”创建矩阵

时间:2020-10-15 00:15:36

标签: matlab loops for-loop

我是MATLAB的初学者,所以对此有一个疑问。我应该怎么写这段代码,如果有机会,有人可以友好地写出代码,因为我一直在努力。使用循环创建3 x 5矩阵,其中每个元素的值是其行号的一半加其列号的三倍。例如,元素(2,5)的值为:1/2 2 + 3 5

2 个答案:

答案 0 :(得分:0)

嵌套循环控制矩阵的索引。外部for循环遍历矩阵的行,内部for循环遍历矩阵的列。

这个问题的第二部分要求结合使用循环/扫描变量RowColumn来设置矩阵的值:

矩阵值=(行÷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

结果:

Matrix Values

循环方法:

Looping Methodology

在工作区中打开的变量矩阵:

Matrix Array

答案 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