ubnewb
ubnewb

Reputation: 341

Octave how to compare matrix elements efficiently

I have a large matrix and I would like to compare the adjacent elements to verify that the values are close to being equal.

For example, in this sequence 1006, 1004,999, 1000, 1003, 6, 1005, 1003 ..... the value 6 is not "close to" 1003 or 1005. I would like an efficient method for doing the comparison.

Here is slow code to find anything outside of the range. It takes 190 seconds on my old computer.

Thank you.

big = 1e5;
tic;
a = 0;
x = rand(100,big);
for ii = 1:100
  for jj = 1:big-1;
    y = x(ii,jj) / x(ii,jj+1);
    if (or(y < 0.999,y > 1.001))   a++;
    endif  
  endfor;
endfor;
toc

Upvotes: 1

Views: 364

Answers (1)

rahnema1
rahnema1

Reputation: 15857

Use vectorization instead of loop:

y = x(:, 1:end-1) ./ x(:, 2:end);
a = nnz(y < 0.999 | y > 1.001);

Upvotes: 3

Related Questions