Extracting and summing data from a 3d matrix
18 views (last 30 days)
Show older comments
Hi there,
I have some data in a 3d matrix 11*32*19. I want to a) identify all columns where there is a non-NaN and b) identify the blocks of non-NaNs (from 1 row long to 11 rowns long) and sum together the blocks in each of the 32 columns, giving a total value for each column against the column name for all the 19 'pages' combined. I have some code to do that for a 2d matrix (below), although i am just realising that it will miss the blocks that start at row 1 :/ so any suggestions on that front would be awesome too.
filename = '1001_1_2';
[locAll,typeAll]=find(isfinite(mVocs)); %extracting the locations of all the non NaNs (finite numbers)
indVocsAll=any(isfinite(mVocs));
colindx = find(indVocsAll==1);
colres = zeros(length(colindx),1);
for i =1:length(colindx)
tmpdat = mVocs(:,colindx(i));
blocklength = zeros(length(tmpdat),1);
for fi = 1:length(tmpdat)-1
if isnan(tmpdat(fi)) && ~isnan(tmpdat(fi+1)) %finding where the column goes from NaN to 1
count = fi+1;
count2 = 1;
while ~isnan(tmpdat(count)) %also count Non-Na
count = count+1;
count2 = count2+1;
end
%tmpdat2 = tmpdat(fi+1:fi+count2-1);
blocklength(fi) = count2;
end
end
blocklength = nonzeros(blocklength);
savename = strcat(savedir, 'filename.mat');
save(savename, 'blocklength');
colres(i) = length(blocklength);
colres(:,2) = colindx;
end
by counting the start of the number of blocks in each column - i am just realising that it will miss the blocks that start at row 1 :/ so any suggestions on that front would be awesome too.
8 Comments
Answers (1)
Nipun
on 27 Sep 2023
Hi Emu,
I understand that you have a three dimensional matrix with dimensions: 11,32,19 with few NaN values. And, you are trying to get a sum-block output against each column which has a non-NaN value. I assume that the output will be a 32 x 19 matrix with one summation for each column across all rows.
In the example code below, I have generated a random matrix with the required dimensions. Please refer to the documentation for sum function in MATLAB for any clarifications.
M = rand(11,32,19);
% Generate 100 random indices to make them nan
idx = [];
for i=1:12000
x = randi(size(M,1),1);
y = randi(size(M,2),1);
z = randi(size(M,3),1);
idx = [idx [x,y,z]];
M(x,y,z) = NaN;
end
% sum over all rows for each column across all 'pages' (3rd dimension)
A = sum(M,1,"omitnan");
size(A)
Hope this helps.
Regards,
Nipun
0 Comments
See Also
Categories
Find more on Time Series Events in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!