How to obtain the row and column indices of a "bsxfun" matrix

I have a code as follows:
A=rand(1,100);
B=rand(1,1000);
idx=bsxfun(@minus,A(:,1),B(:,1)')<0.2;
I want to make a matrix C, in which each cell gets a value if the corresponding cell of "idx" is 1. I wrote the following code:
C=zeros(100,1000);
C(idx)=C(idx)+array_1(1,i)+array_2(1,j);
In which array_1 and array_2 are two row vectors. Furthermore, "i" is the row index of each nonzero element of "idx", and "j" is the column index of each nonzero element of "idx". In other words, in each nonzero cell of "idx", I should know the row and column indices separately, so that array_1 and array_2 can be applied.
I know that the last line might be incorrect, but I don't know how to correct that. Any comment or hint is really appreciated!
Thank you!

1 Comment

I must be missing something.
A and B are both row vectors, so you are always subtracting A(1,1) from B(1,1), testing to see if that value is less than 0.2, then assigning that logical value to idx. The value of idx will be either 1 or 0. (The 0 result will throw an error if you try to use it later as an index.)
This doesn't make sense to me.
Please explain in some detail what you want to do with A, B, and C.
(Also I suggest you do not use i or j as array or loop indices. MATLAB uses them for its imaginary operators, so this will cause confusion if you have complex numbers.)

Sign in to comment.

 Accepted Answer

Use IND2SUB or FIND with the two output option. By the way, you do realize that idx is scalar as you have it, right? What you may want is:
A=rand(1,100);
B=rand(1000,1);
idx=bsxfun(@minus,A,B)<0.2;
which we can make directly:
idx = (rand(1000,100)-rand(1000,100))<.2;

3 Comments

Thank you! So, can I write something like this?
s=[100,1000]; [X,Y]=ind2sub(s,idx); C(idx)=C(idx)+array_1(1,X)+array_2(1,Y);
Again, the last line seems to be problematic.
C = rand(1000,100);
idx = (rand(1000,100)-rand(1000,100))<.2;
array_1 = randperm(1000);
array_2 = randperm(100);
[X,Y]=find(idx);
C(idx)=C(idx)+array_1(X).'+array_2(Y).';
Thank you very much Matt! You helped a lot.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!