如何正确循环遍历一个简单的二维矩阵?

How can I properly loop through a simple 2D matrix?

我不明白为什么我找不到任何明确的答案!这么基础的东西...

我有一个普通的二维矩阵,比如这个:

matrix = zeros(w, h);

其中w, h ∈ Z+,表示wh是大于零的正整数。

我需要遍历矩阵并对它的元素做一些事情。对于这个任务,我们可以假设 h=3。因此,我尝试了这个:

        test = zeros(w, 3);
        for i = 1:test
            point = test(:,i);
            [point(0), point(1), point(2)] = MY_CONVERSION(point(0), point(1),point(2));
            test(:,i) = point;
        end

MY_CONVERSIONvarargin 函数,3 个参数定义为:

function [rho, alpha, z] = MY_CONVERSION(r, alpha, epsilon) 

当然,在实际代码中 test 包含数据,而不仅仅是零。但是仅此代码就可以,例如,用随机数填充矩阵。但是没用。

我还尝试使用三个变量来存储列值:

        for i = 1:Xi
            [a,b,c] = Xi(:,i);
            [a,b,c] = mysph2cyl(a, b, c);
            rho(:,i) = a,b,c;
        end

Matlab 将其标记为语法错误:

An assignment statement makes an assignment to multiple values, but the expression on the right side of the assignment does not appear to produce multiple values.

第一段代码是您需要让它工作的代码。但是,您的 for 循环不正确。您可能想要遍历所有 ,因此 for i = 1 : size(test,2) 而不是 testsize(test,2) 确定您的矩阵有多少列。

因此:

    test = zeros(w, 3);
    for i = 1:size(test,2) %// Change here
        point = test(:,i);
        [point(0), point(1), point(2)] = MY_CONVERSION(point(0), point(1),point(2));
        test(:,i) = point;
    end

此外,您的第二段代码需要像我上面提到的那样修复 for 循环问题。 for 循环中的第一条语句是多余的。你不需要它。第三行代码需要有[]包围a,b,c.

首先,matrix = zeros(w, h); 造成混淆:您可能认为 w 是宽度,h 是高度。但是zeros的第一个参数是高度:比如zeros(2,3)就是

 0     0     0
 0     0     0

一般来说:行索引在前,列索引在后。

然后你有 for i = 1:test 但 test 是一个矩阵。你在这里需要一个号码。

这是一个类似于您的第一个片段的工作示例:

w = 2; h =3;        
test = zeros(w, h);
for i = 1:h
    point = test(:,i);
    point = cos(point)*i;  % sample conversion
    test(:,i) = point;
end

输出:

1     2     3
1     2     3