Force nansum to equal NaN (and not 0)

조회 수: 3 (최근 30일)
Christoffer Benneballe
Christoffer Benneballe 2020년 1월 28일
댓글: Christoffer Benneballe 2020년 1월 29일
Hi Mathworks
I have had a lot of luck with previous questions, so I will try once more. The question have sort of already been answered before here, but I can seem to get the suggestion to work:
Basically, I have a matrix of some numbers (and a lot of NaNs) that I want to multiply by a similar matrix and take the nansum (line 168-171) as:
for i = 1:(size(retSize1Value1,1))
tmp_i = nansum(omega(i,:).*retSize1Value1(i,:));
returnMarket(i,1) = tmp_i(1);
end
returnMarket(all(isnan(omega)&isnan(retSize1Value1),1)) = NaN;
I have tried the suggestion in the other post (line 173) after the for loop.
Later I will take the mean, so the issue is, that if nansum is a product of NaNs Matlab fill out the value to zero and not NaN!
I hope you will save me once more.
All the best,
Christoffer

채택된 답변

Spencer Chen
Spencer Chen 2020년 1월 28일
Try:
returnMarket(all(isnan(omega)&isnan(retSize1Value1),2)) = NaN;
You need to run all() on dimension 2 instead of dimension 1.
A few more tips on your code:
1. You will find your problem easier to debug if you reduce the complexity of your expressions. i.e. Code the above line in 2 steps:
nanmask = all(isnan(omega)&isnan(retSize1Value1),2);
returnMarket(nanmask) = NaN;
2. Your for loop can be easily converted into matrix operations, which tends to improve speed and helps you to think more Matlab-like. I believe the below produces an equivalent result to your for loop:
tmp_i = omega .* retSize1Value1;
returnMarket = nansum(tmp_i,2);
Blessings,
Spencer
  댓글 수: 1
Christoffer Benneballe
Christoffer Benneballe 2020년 1월 29일
Thank you, Spencer!
It works now - really nice!
And appreciate your suggestions - I cannot seem to get the second part to function as suggested under 2.
Tried to implement it as follows and also tried to comment out the last term. I just get returnMarket = 0.
for i = 1:(size(retSize1Value1,1))
tmp_i = nansum(omega(i,:).*retSize1Value1(i,:));
returnMarket = nansum(tmp_i,2);
returnMarket(i,1) = tmp_i(1);
end

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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by