Matlab:使用矩阵运算而不是for循环 [英] Matlab: using matrix operations instead of for loops

查看:252
本文介绍了Matlab:使用矩阵运算而不是for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Matlab中只使用矩阵操作来创建一个NxN矩阵,就像下面两个foor循环会做的那样

Is it possible in Matlab to use only matrix operations in order to create a NxN matrix Mat like the following two foor loops would do?

Mat = zeros(N);
for row = 1:N
    for col = 1:N
        if (row == 1 && (1 <= col && col <= N))
            Mat(row,col) = N;
        end
        if ((2 <= row && row <= N) && (1 <= col && col <= N))
            Mat(row,col) = (2*row+1)*col;
        end
    end
end

我想索引相应的行和列:

I thought indexing the corresponding rows and columns like:

Mat(1,1:N) = N;

row = 2:N;
col = 1:N;
Mat(row,col) = (2.*row+1).*col;

第一行正在工作。
但是第二个操作明显地导致了行和列的尺寸问题。

The first line is working. But the second operation leads obviously to a problem with the dimensions of row and col.

如何使用row和col的每个值?
还是有一个简单的方法来实现从两个foor循环相同的结果吗?

How can I use each value of row and col? Or is there a simpler way of achieving the same result from the two foor loops?

推荐答案

您也可以使用 ndgrid ;

You could also use ndgrid;

[II,JJ] = ndgrid(1:N);
Mat = JJ+2*JJ.*II;
Mat(1,:) = N;

这篇关于Matlab:使用矩阵运算而不是for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆