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 件のコメント

Star Strider
Star Strider 2012 年 9 月 6 日
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.)

サインインしてコメントする。

 採用された回答

Matt Fig
Matt Fig 2012 年 9 月 6 日
編集済み: Matt Fig 2012 年 9 月 6 日

0 投票

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 件のコメント

Alireza
Alireza 2012 年 9 月 6 日
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.
Matt Fig
Matt Fig 2012 年 9 月 6 日
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).';
Alireza
Alireza 2012 年 9 月 6 日
Thank you very much Matt! You helped a lot.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by