0
votes

Assume we have nxn binary matrix M. In MATLAB, I want to find the "average" index of points that correspond to 1.

To illustrate, the following examples are shown. A red circle indicates a cell value of 1, all other cell values are 0. The green x is the index that I want to return. A blue line of best fit further illustrates my point.

enter image description here

I am specifically looking for efficient code to do this. Anyone with some simple math skills can calculate this "average" index, but due to MATLAB's loop/iteration-based inefficiencies, I need to write fast code.

1
but due to MATLAB's inefficiencies what inefficiencies? Matlab can handle it pretty well. Matlab is very good at handling matrices. - CroCo
Loops are extremely expensive in MATLAB. Particularly nested loops. In my specific case, what I am implementing is already in a nested loop, and so any additional loops would be highly undesirable. - Stephen Lasky
Take a look at Vectorization in Matlab. - CroCo
I understand the various methods of increasing performance in Matlab. This is beyond the scope of this question and ultimately irrelevant. However, for the sake of simplicity assume the above nested loops are unavoidable and thus the inner code need be highly efficient. - Stephen Lasky
highly efficient in which sense? Also, in Matlab, you can call C code if this is what you're looking for. - CroCo

1 Answers

1
votes

How about this:

Rand_matrix=randi([0 1],3,3); %random binary matrix
[rows,col]=find(Rand_matrix);
row_mean=mean(rows);
col_mean=mean(col);
midpoint=[row_mean,col_mean]