0
votes

I am trying to sum in the second dimension a matrix QI in Matlab. The trick is, the columns contain a series of increasing numbers, but not all columns have the same number of elements (i.e. numel(QI(:,1)) ~= numel(QI(:,2)) and so on). For the sake of clarity, I attach a picture of it. Note that I padded the missing areas with 0, so the previous condition becomes nnz(QI(:,1)) ~= nnz(QI(:,2)).

Matrix QI

One initial strategy that I thought of was to treat this as an image and construct a mask for each different gradient level, but that seems like a tedious job.

Colored QI

Anyone has a better idea on how to do this? I should also mention that I am able to freely modify how QI is generated, but I'd rather not if there is a solution for this problem.


EDIT:

Hopefully the new colored image should give a better understanding.

FYI, each column was previously stored in a cell array without the trailing zeros. Then I extracted the columns one by one and stored them in a matrix in order to perform the summation, padding the extra zeros whenever the length isn't the same.

Generally these column data should have the same number of rows, but sometimes that's not the case, and even worse, they do not allign properly.

I'm starting to think if it's better to rework the code that generate the cell arrays rather than this matrix. Thoughts?

Thank you,

1
So what's the problem? Sum the rows (or did you mean to sum in the first dimension?) and the zero elements don't contribute to the sum.beaker
I would've done that, except that it doesn't solve the problem. I'll try and reformulate it.KaiserHaz
Yes, you need to change the way you convert your data. Depending on the structure of the cell array, you might not even have to create the full matrix, but there's no way of knowing without more information.beaker

1 Answers

0
votes

edit: following you comment, I modified the answer. Be aware that your data cannot be really "aligned" because they have not the same number of value.

A way would be to use a cell as a storage for your measures.

valueMissing   =  0; % here you can put the defauld value you want

% transform you matrix in a cell
QICell = arrayfun(@(x) QI(QI(:,x)!=valueMissing,x), 1:size(QI,2),'UniformOutput', false);

Now you can sum the last element of the vectors inside the cell

QIsum = sum(cellfun(@(x) x(end), QICell))

Or reorder the vectors so that your last element are "aligned"

QICellReordered = cellfun(@(x) x(end:-1:1),QICell, 'UniformOutput',false);

Then you can make all possible sums:

m = min(cellfun(@numel, QICellReordered));
QIsum = zeros(m,1);

for i=1:m
    QIsum(i) = sum(cellfun(@(x) x(i), QICellReordered));
end

% reorder QISum to your original order
QIsum = QIsum(end:-1:1);

I hope this help !