Change specific values in odd/even columns of a matrix

21 ビュー (過去 30 日間)
Miquel
Miquel 2019 年 9 月 25 日
コメント済み: Star Strider 2019 年 9 月 25 日
I have a matrix and I would like to make all values which are equal x, equal to y. But I would like to do that only in odd columns. Can I do it without using a loop?
Say I have the following matrix:
>> A=randi([1,5],4,4)
A =
5 4 5 5
5 1 5 3
1 2 1 5
5 3 5 1
And I would like to turn all 1's which are in the odd columns into 0's to get the following matrix:
5 4 5 5
5 1 5 3
0 2 0 5
5 3 5 1
I tried to do the job with this code:
A(A(:,1:2:end)==1)=0
A =
5 4 5 5
5 1 5 3
0 0 1 5
5 3 5 1
It gets the position of the 1's in the odd columns right, but it changes the values in consecutive columns instead.
I guess an equivalent question would be how to generate a logical matrix of the same dimensions of A with all values equal to 0 except these which are equal to 1 AND in odd columns.
Any ideas?
Thanks

採用された回答

Star Strider
Star Strider 2019 年 9 月 25 日
Try this:
A = [5 4 5 5
5 1 5 3
1 2 1 5
5 3 5 1];
L = A == 1;
L(:,2:2:end) = false;
A(L) = 0
producing:
A =
5 4 5 5
5 1 5 3
0 2 0 5
5 3 5 1
  2 件のコメント
Miquel
Miquel 2019 年 9 月 25 日
Thanks! Easy to understand :)
Star Strider
Star Strider 2019 年 9 月 25 日
As always, my pleasure!

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

その他の回答 (1 件)

Fabio Freschi
Fabio Freschi 2019 年 9 月 25 日
% find all values
[iRow,jCol] = find(A == 1);
% find odd rows
iOdd = rem(jCol,2) ~= 0
% fix values
A(sub2ind(size(A),iRow(iOdd),jCol(iOdd))) = 0;
  1 件のコメント
Miquel
Miquel 2019 年 9 月 25 日
Thanks! It took me a bit to get all the steps but it is a very good answer :)

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by