如何在不首先将其分配给局部变量的情况下索引函数返回的MATLAB数组? [英] How can I index a MATLAB array returned by a function without first assigning it to a local variable?

查看:331
本文介绍了如何在不首先将其分配给局部变量的情况下索引函数返回的MATLAB数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我想从 magic(5)中读取中间值,我可以这样做:

For example, if I want to read the middle value from magic(5), I can do so like this:

M = magic(5);
value = M(3,3);

获取 value == 13 。我希望能够做到以下其中一项:

to get value == 13. I'd like to be able to do something like one of these:

value = magic(5)(3,3);
value = (magic(5))(3,3);

免除中间变量。但是,MATLAB在 3 之前的第一个括号上抱怨不平衡或意外的括号或括号

to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.

是否有可能从数组/矩阵中读取值而无需先将其赋值给变量?

Is it possible to read values from an array/matrix without first assigning it to a variable?

推荐答案

实际上 可以做你想要的,但你必须使用索引操作符的功能形式。使用()执行索引操作时,实际上是在调用 subsref 功能。所以,即使你不能这样做:

It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:

value = magic(5)(3, 3);

可以这样做:

value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));

丑陋但可能。 ;)

通常,您只需将索引步骤更改为函数调用,这样就不会有两组括号紧跟在一起。另一种方法是定义自己的匿名函数做下标索引。例如:

In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:

subindex = @(A, r, c) A(r, c);     % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3);  % Use the function to index the matrix

然而,当所有的说完成并临时局部变量解决方案时很多更具可读性,绝对是我的建议。

However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.

这篇关于如何在不首先将其分配给局部变量的情况下索引函数返回的MATLAB数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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