Combine several matrix with NaNs

5 ビュー (過去 30 日間)
Jules Ray
Jules Ray 2018 年 1 月 7 日
回答済み: Aditya 2025 年 1 月 23 日 13:30
I need to combine several matrixes of 500x500 elements that contains NaN. The matrixes must be combined in the way they keep their size but replace NaN by the elements of the other matrix.
I can easily do it for two matrixes: % Cx is a strucutre that I use to store these matrixes. Cx has several matrixes e.g Cx(1).Z Cx(2).Z ...
or=Cx(1).Z; %I want to add the elements to the first matrix (or)
nr=Cx(2).Z; % this is the second matrix
xn=isnan(or); %I select the NaN's
or(xn)=nr(xn); %I can get now combined elements between Cx(1).Z and Cx(2).Z, it works good until here
%I need to do the same now for all the other matrixes in my structure (Cx),so the combination will be cummulative, I mean use the resulting matrix from merging Cx(1).Z and Cx(2).Z to merge with Cx(3).Z, and then use this output to merge with Cx(4).Z .... and so on
I tough that a loop would be usefull
or=Cx(1).Z;
xn=isnan(or);
for i=1:numel(Cx)
nr=Cx(i).Z;
or(xn)=nr(xn);
end
but the output or is constantly overwrited and I can get a combination of the matrixes
any suggestion?
thanks in advance

回答 (1 件)

Aditya
Aditya 2025 年 1 月 23 日 13:30
Hi Jules,
To combine multiple matrices while replacing 'NaN' values with corresponding elements from other matrices, you can indeed use a loop. However, the issue in your current approach is that you're not updating the 'xn' (NaN indices) after each iteration, which causes only the 'NaN' values from the first matrix to be replaced.
Here's how you can modify your code to achieve cumulative merging:
% Initialize 'or' with the first matrix
or = Cx(1).Z;
% Loop through each subsequent matrix
for i = 2:numel(Cx)
nr = Cx(i).Z;
% Find NaN indices in the current 'or' matrix
xn = isnan(or);
% Replace NaN values in 'or' with values from the current matrix 'nr'
or(xn) = nr(xn);
end
% 'or' now contains the combined matrix with NaNs replaced

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by