logical operation on a column within a matrix

I have the m-by-n matrix POS
I want to focus on a single column and perform an element-wise logical operation. For instance, turning all zero's to ones:
POS(POS(:,2)==0)=1;
However, this does nothing. On the other hand, this works on the whole matrix:
POS(POS==0)=1;
But, obviously, I just want to perform this operation on column 2. What am I missing? I do not want another line of code since speed is very important here.
Even more confusing, the following works on the first column, but not on the second:
POS(POS(:,1)==1)=2; % works
POS(POS(:,2)==1)=2; % not working

 採用された回答

lvn
lvn 2014 年 2 月 28 日

0 投票

This should work:
POS(POS(:,2)==0,2)=1;

2 件のコメント

Christopher
Christopher 2014 年 2 月 28 日
Thanks. But why does it work? Where can I read more about this type of referencing?
lvn
lvn 2014 年 2 月 28 日
編集済み: lvn 2014 年 2 月 28 日
filter=(POS(:,2)==0)
gives you a vector (of 0's and 1's).
POS(filter)=1
normally assumes 'filter' to be a matrix. This is why filter=(POS==0) gives you the expected answer. What you want is just to change the second column, hence you only want to target the second column:
POS(filter,2)=0
This tells matlab to change only the second column, using the filter as argument. Note sure this is very clearly explained, but read more here http://www.mathworks.com/help/matlab/math/matrix-indexing.html

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

その他の回答 (0 件)

カテゴリ

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

製品

質問済み:

2014 年 2 月 28 日

編集済み:

lvn
2014 年 2 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by