Reputation: 39
Let A
be a sparse matrix in coordinate format [row(int) col(int) val(float)]
. If a upper triangular sparse matrix of A
is needed, then the same can be obtained using logical indexing like:
A = A(A(:,1) <= A(:,2), :);
If A is cell array [{row(int)} {col(int)} {val(string)}]
, how do I perform the same logical indexing as above in this case?
Upvotes: 0
Views: 835
Reputation: 1744
How about this:
A = A(cellfun(@(x,y) x>=y, A(:,1),A(:,2)),:);
That should only keep the rows in which the value in the first column is greater than or equal to the value in the second column. You can change the x>=y
comparison to anything you want, including string comparisons, etc.
Upvotes: 1
Reputation: 16035
You can use cell2mat
to transform a column of the cell into a matrix that can be used as an index list:
A={1,2,'top';2,1,'bottom'}
A =
[1] [2] 'top'
[2] [1] 'bottom'
>> A(cell2mat(A(:,1))<=cell2mat(A(:,2)),:)
ans =
[1] [2] 'top'
Upvotes: 2
Reputation: 16035
Why not using matlab built-in sparse matrix format?
Create a sparse matrix:
>> A=sparse([1 2],[2 1],1,2,2)
A =
(2,1) 1
(1,2) 1
Extract upper triangular part:
>> triu(A)
ans =
(1,2) 1
Upvotes: 0