Ignore NaN values in a Table

20 views (last 30 days)
Nicholas Thomason
Nicholas Thomason on 11 Oct 2021
Commented: Nicholas Thomason on 11 Oct 2021
Hello - apologes if this has been covered previously, but i can't find a satisfactory answer; any help would be greatly appreciated!
I have a table, called "returns" (% performance for some investments), see below. Some cells are NaN.
I wish to compute a range of statistics based on these numbers: annualised return / annualised volatiity / contribution to return / contribution to volatility / contribution to drawdown etc.
Date return1 return2 return3 return4
....
'30-Apr-2020' 0.056 0.0097 0.0467 0.0240
'31-May-2020' NaN 0.0152 0.0635 0.0450
How can i ignore this NaN value? For example, if i take the example of contribution to return, with the code below. Simply put, how do I ignore the NaN when calculateing the annualized return for each (the first section, highlighed in bold). This code below will return annualized return for funds 2, 3 and 4, but for fund 1, with the NaN - it will not work.
%% CONTRIBUTION TO RETURN
% annualized returns for each fund I
I = (prod(returns+1).^(12/length(returns)))-1;
% weighted annualized return
I_W = I .* weights;
% portfolio returns, monthly and annualized
% amended: portfolio returns taken direct from SP - appropriate rebalancing
% of portfolio when fund track not available
%monthly_fund_contrib = returns .* weights;
%portfolio_return = sum(monthly_fund_contrib')';
portfolio_return = outputdata2(:,2); %ensure this is double
portfolio_return = cell2mat(portfolio_return);
R = (prod(portfolio_return+1).^(12/length(portfolio_return)))-1;
% difference between portfolio return and sum of contributions
Diff = R - sum(I_W);
% weight this difference across funds in the portfolio
Diff_W = weights * Diff;
Return_Contribution = I_W + Diff_W;
Return_Contribution = array2table(Return_Contribution);
many thanks for any help!

Answers (2)

Star Strider
Star Strider on 11 Oct 2021
Since the Question appears to apply to the prod funciion, see the section on Product Excluding NaN. (I am not certain when that option was introduced, however it is present in all recent versions/releases.)
.

Lalitha Tejaswi
Lalitha Tejaswi on 11 Oct 2021
The functions prod and sum have an option to provide the nanflag where you can include the NaNs (use 'includenan') or omit the nans ('omitnan') while you use these functions.
Example: For computing the product of the following array elements without considering NaNs,
x = [1 2 3 NaN];
product = prod(x,'omitnan')
product = 6
Same goes with sum. Use this option for your computations.
Hope this helps!

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!