MATLAB Answers

0

MATLAB syntax (parantheses without intermediate steps)

Christian Huggler さんによって質問されました 2019 年 11 月 5 日
最新アクティビティ dpb
さんによって 編集されました 2019 年 11 月 5 日
dpb
さんの 回答が採用されました
Why is following intermediate calculation step necessary?
temp = abs(rand(10)-eye(10));
result = mean(temp(:));
In Octave is it possible to write the same on one single line:
result = mean(abs(rand(10)-eye(10))(:));

  0 件のコメント

サインイン to comment.

製品


リリース

R2019b

3 件の回答

dpb
回答者: dpb
2019 年 11 月 5 日
編集済み: dpb
2019 年 11 月 5 日
 採用された回答

Because to date TMW has chosen to not implement post-addressing expressions on results.
"WHY?" you'd have to ask TMW and it's unlikely they will discuss such internals design decisions/plans publicly.
You can write the expression on one line in MATLAB, too, just more explicitly...
result = mean(mean(abs(rand(10)-eye(10)))); % is one common idiom for 2D arrays
or
result = mean(reshape(abs(rand(10)-eye(10))),:,1); % is generic

  0 件のコメント

サインイン to comment.


Fangjun Jiang
回答者: Fangjun Jiang
2019 年 11 月 5 日

mean(mean(abs(rand(10)-eye(10))))

  3 件のコメント

Jan
2019 年 11 月 5 日
Or easier:
mean(mean(abs(rand(10) - eye(10))))
% Or:
mean(abs(rand(10) - eye(10)), 'all')
[EDITED] I have confused eye(10) with ones(10). Fixed now.
Christian Huggler 2019 年 11 月 5 日
My code is just an example. You're right, it works with calling "mean" twice. But let's change the example to "median" - matematical not the same on using this function twice.
Steven Lord
2019 年 11 月 5 日
That fails to behave the same way as the original code if the inputs have more than 2 dimensions.
x = rand(3, 4, 5);
mean(mean(abs(x - 0.5)))

サインイン to comment.


Steven Lord
回答者: Steven Lord
2019 年 11 月 5 日

That intermediate step isn't necessary in this case, since you're using a release that supports the 'all' dimension input argument to mean. I'll create the data as separate variables so you can check that the two-step and one-step approaches give the same result.
x = rand(10);
temp = abs(x-eye(10));
result1 = mean(temp(:));
result2 = mean(abs(x-eye(10)), 'all');
isequal(result1, result2) % true

  0 件のコメント

サインイン to comment.



Translated by