MATLAB syntax (parantheses without intermediate steps)
Show older comments
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))(:));
Accepted Answer
More Answers (2)
Fangjun Jiang
on 5 Nov 2019
mean(mean(abs(rand(10)-eye(10))))
3 Comments
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
on 5 Nov 2019
Steven Lord
on 5 Nov 2019
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)))
Steven Lord
on 5 Nov 2019
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
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!