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

查看:25
本文介绍了如何在不先将函数返回的 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 之前的第一个括号上抱怨 Unbalanced or unexpected parenthesis or括号.

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天全站免登陆