## Monday, November 22, 2010

### Matlab weirdness: Creating Logical Arrays and Accessing Sparse Matrices

While trying out the new Constrained Parametric Min Cuts code, I came across some Matlab weirdness.
Given a huge sparse matrix X and some row and column indices r and c, I wanted to pick out these elements.
As usual, I called
ind=sub2ind(size(X),r,c)
Y=X(ind)

... and got an out of memory error.
That seemed a little weired, since "ind" wasn't that long.
It seemed to me as if the matrix is converted into a full (=dense) matrix before the linear indexing took place.
After quite some thinking and searching on the web, I came across a post about the same problem.
Apparently the "correct" solution to my problem is:
[I J x]=find(X);
[tf loc]= ismember([r(:) c(:)],[I J],'rows');
Y = zeros(size(tf));
Y(tf) = x(loc(tf));

why this is so, I have no idea. Maybe someone can clear this up for me.

At some point in the code, a large logical array has to be generated.
This was done with zeros().
I thought to myself "Well this is no good. This surely should be a logical array."
And so I tried
X=zeros(w,h,'logical')

... and failed.
While
X=zeros(w,h,'int8')

worked perfectly.
Again, the web helped out.

The "correct" solution here is to do
X=false(w,h)

Who would have thought.

#### 1 comment:

1. Thanks for posting. X=false(w,h) is exactly what I was looking for