0

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?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Stoka
  • 39
  • 7

3 Answers3

2

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'
Oli
  • 15,935
  • 7
  • 50
  • 66
1

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.

nispio
  • 1,743
  • 11
  • 22
0

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
Oli
  • 15,935
  • 7
  • 50
  • 66
  • thank you for your answer and question. I can't use matlab built-in sprase matrix format because the values are all strings. – Stoka Nov 06 '13 at 05:08