MATLAB syntax (parantheses without intermediate steps)

조회 수: 1 (최근 30일)
Christian Huggler
Christian Huggler 2019년 11월 5일
편집: dpb 2019년 11월 5일
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))(:));

채택된 답변

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

추가 답변 (2개)

Fangjun Jiang
Fangjun Jiang 2019년 11월 5일
mean(mean(abs(rand(10)-eye(10))))
  댓글 수: 3
Christian Huggler
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
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)))

댓글을 달려면 로그인하십시오.


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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by