poster
2019-12-10, 20:48
例如,如果我想从magic(5)读取中间值,可以这样进行:
M = magic(5); value = M(3,3); 获得value == 13 。我希望能够执行以下操作之一:
value = magic(5)(3,3); value = (magic(5))(3,3); 取消中间变量。但是,MATLAB抱怨3之前的第一个括号Unbalanced or unexpected parenthesis or bracket括号。
是否可以在不首先将其分配给变量的情况下从数组/矩阵读取值?
回答:
它实际上是可以做到你想要什么,但你必须使用索引操作符的功能形式。当您使用()执行索引操作时,实际上是在调用subsref (https://www.mathworks.com/help/matlab/ref/subsref.html)函数。因此,即使您不能执行此操作:
value = magic(5)(3, 3); 您可以这样做:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}})); 丑陋,但可能。 ;)
通常,您只需将索引步骤更改为函数调用,这样就不会紧接着紧跟着两组括号。做到这一点的另一种方法是定义自己的匿名函数 (https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html)来进行下标索引。例如:
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 然而,当一切都说过和做过临时局部变量的解决办法是更可读,肯定我的建议。
更多&回答... (https://stackoverflow.com/questions/3627107)
M = magic(5); value = M(3,3); 获得value == 13 。我希望能够执行以下操作之一:
value = magic(5)(3,3); value = (magic(5))(3,3); 取消中间变量。但是,MATLAB抱怨3之前的第一个括号Unbalanced or unexpected parenthesis or bracket括号。
是否可以在不首先将其分配给变量的情况下从数组/矩阵读取值?
回答:
它实际上是可以做到你想要什么,但你必须使用索引操作符的功能形式。当您使用()执行索引操作时,实际上是在调用subsref (https://www.mathworks.com/help/matlab/ref/subsref.html)函数。因此,即使您不能执行此操作:
value = magic(5)(3, 3); 您可以这样做:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}})); 丑陋,但可能。 ;)
通常,您只需将索引步骤更改为函数调用,这样就不会紧接着紧跟着两组括号。做到这一点的另一种方法是定义自己的匿名函数 (https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html)来进行下标索引。例如:
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 然而,当一切都说过和做过临时局部变量的解决办法是更可读,肯定我的建议。
更多&回答... (https://stackoverflow.com/questions/3627107)