Combine several matrix with NaNs
조회 수: 3 (최근 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
댓글 수: 0
답변 (1개)
Aditya
2025년 1월 23일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!