Matlab:默认变量隐式地知道矩阵中的索引位置? [英] Matlab: default variables to know the index positions in a matrix implicitly?
问题描述
ii
表示 x轴
中的索引, jj 表示 y轴
中的索引值。这个例子运行一个2x2倍的单矩阵。 Matlab是否有一些准备好的命令用于索引值 ii
和 jj
,所以我可以避免for-looping?
输入:尝试寻找隐式解决方案,但要求位置信息(ii,jj)
@(a)a + ii + jj; h(ones(2))
输出结果
$ b $ (1 + 1)1+(2 + 1)
4 5 = 1+(1 + 2)1+(2 + 2)b
Ps代码味道:明确的解决方案,不是这样的!
hh = ones(2); (ii,jj)= hh(ii,jj)+ ii + jj
结束
$ 2
对于ii = 1:2
end
解决方案 h = @(a)一种+ II + JJ;
h(ones(2))
据我所知Matlab没有 ii
或 jj
就像你想要的一样。这不是Matlab的工作原理。我建议你看一看meshgrid:
Input = ones(2);
[N,M] = size(Input);
[jj,ii] = meshgrid(1:M,1:N);
hh = jj + ii +输入
meshgrid
生成两个矩阵,可以指定矩阵的行和列坐标。我觉得你太习惯于使用其他语言的编程风格了。如果您使用的是Matlab,我建议您尝试使用原生最佳实践风格。
The ii
means the index in the x-axis
and the jj
means the index value in the y-axis
. This example runs over a 2x2 times one-matrix. Does Matlab have some ready commands for the index values ii
and jj
so I can avoid for-looping?
Input: trying to find a implicit solution but requires the location info (ii,jj)
h=@(a)a+ii+jj; h(ones(2))
Intented output
3 4 1+(1+1) 1+(2+1)
4 5 = 1+(1+2) 1+(2+2)
P.s. Code-smell: Explicit solution, not like this!
hh=ones(2);
for ii=1:2
for jj=1:2
hh(ii,jj)=hh(ii,jj)+ii+jj
end
end
解决方案 h=@(a)a+ii+jj;
h(ones(2))
As far as I know Matlab does not have an ii
or jj
built in like you want. That's not how Matlab works. I suggest you have a look at meshgrid:
Input = ones(2);
[N, M] = size(Input);
[jj, ii] = meshgrid(1:M, 1:N);
hh = jj + ii + Input
meshgrid
generates two matrices that can specify row and the column coords of a matrix. I think you're getting too hung up on programming styles from other languages. If you're using Matlab, I suggest you try stick to the native best practice styles.
这篇关于Matlab:默认变量隐式地知道矩阵中的索引位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文