基于索引初始化MATLAB矩阵 [英] Initialize MATLAB matrix based on indices

查看:118
本文介绍了基于索引初始化MATLAB矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个满足以下条件的矩阵M:

I'm trying to create a matrix M satisfying:

M(i,j) = f(i,j)

一些.我可以通过说M = zeros(m,n)然后循环来进行元素初始化.例如(在八度中):

for some f. I can do elementwise initialization through say M = zeros(m,n) then looping. For example (in Octave):

M = zeros(m,n)
for i = 1 : m
  for j = 1 : n
    m(i, j) = (i+j)/2;
  endfor
endfor

但是AFAIK循环并不是使用MATLAB的最佳方法.有提示吗?

But AFAIK loops are not the optimal way to go with MATLAB. Any hints?

推荐答案

当然!

 xi = 1:m;
 xj = 1:n;
 Ai = repmat(xi',1,length(xj));
 Aj = repmat(xj,length(xi),1);
 M = f(Ai,Aj);

您可以对任何f()进行此操作,只要它接受矩阵参数并进行逐元素数学运算即可.例如:f = @(i,j) (i+j)/2或用于乘法:f = @(i,j) i.*j Ai矩阵的每一行具有相同的元素,Aj矩阵的每一列具有相同的元素. repmat()函数将矩阵(或向量)重复成更大的矩阵矩阵.

You can do this with any f() so long as it takes matrix arguments and does element-by-element math. For example: f = @(i,j) (i+j)/2 or for multiplication: f = @(i,j) i.*j The Ai matrix has identical elements for each row, the Aj matrix has identical elements for each column. The repmat() function repeats a matrix (or vector) into a larger matrix.

我还编辑了上面的内容以提取向量xixj-您将它们作为1:m1:n向量,但是它们可以是任意数值向量(例如[1 2 7.0 pi 1:0.1:20])

I also edited the above to abstract out vectors xi and xj -- you have them as 1:m and 1:n vectors but they can be arbitrary numerical vectors (e.g. [1 2 7.0 pi 1:0.1:20])

这篇关于基于索引初始化MATLAB矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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