0

I have huge n×n matrix A, and the indices of its non-zero elements by a = find(A). I have obtained a new list a1 by deleting some elements from a. I want to have matrix A of indices in a1 without using loops. Any suggestions? Is there any function for this purpose?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Fatime
  • 197
  • 1
  • 5
  • 15

2 Answers2

2

Considering that your matrix is "huge" (and your question implies that it is mostly zeroes), perhaps it would be best if you represent it as a sparse matrix:

[ii, jj] = ind2sub(size(A), a1);
spA = sparse(ii, jj, A(a1), size(A, 1), size(A, 2));

There might be a significant speedup when operating on sparse matrices. If you need to obtain the full matrice back, use full:

newA = full(spA);
Eitan T
  • 32,660
  • 14
  • 72
  • 109
1

Use vector indexing. Without really knowing how "huge" is your matrix A, but assuming you can still handle it in one piece in matlab's memory, just:

B(size(A,1),size(A,2))=0;
B(a1)=A(a1);

Now B is the same as A with only the indexes given by a1.

bla
  • 25,846
  • 10
  • 70
  • 101
  • You should either verify that there is no matrix `B` larger than `A` before running this code, or initialize it explicitly, _e.g_: `B = zeros(size(A));`. – Eitan T May 26 '13 at 08:06
  • if `A` is bigger than say 1000x1000, the initialization I wrote will work faster than the explicit `B = zeros(size(A));`. Choosing `B` assumes no previous matrix named `B` present, I thought that was evident... – bla May 26 '13 at 08:13
  • I know that would work faster, we had a [long discussion](http://stackoverflow.com/questions/14169222/faster-way-to-initilize-arrays-via-empty-matrix-multiplication-matlab) about that, remember? :) What I meant was that you need to make sure that the size of the initialized matrix `B` is correct. P.S: how do you know that `a1` is logical? Did you mean _vector indexing_? – Eitan T May 26 '13 at 08:36
  • yes, I meant vector indexing... thanks for noticing, I'll edit the answer. How can `B(size(A,1),size(A,2))=0;` be of different size than `A` ? what am I missing? – bla May 26 '13 at 08:39
  • Well, if `B` already exists, and say, it's twice the size of `A`, then what you're doing is simply setting one element in `B` to zero instead of resetting the entire matrix. You need to clear `B` before doing this. – Eitan T May 26 '13 at 08:41