Replace Values that Meet a Condition - 3D Matrix

Hi, i have two 3D-Matrices each with a dimension of 3. I work with images and i want to use the rgb-code to create conditions for my needs. The color red got the values of 1 0 0. I want to replace the values of Matrix Z with the values of Matrix X, if Matrix X got the value 1 in dimension 1, the value 0 in dimension 2 and the value 0 in dimension 3. So 1 0 0 for red.
My code for 3D-Matrices X and Z:
Z ( X(:,:,1) == 1 & X(:,:,2) == 0 & X(:,:,3) == 0) = X ( X(:,:,1) == 1 & X(:,:,2) == 0 & X(:,:,3) == 0);
The result is not satisfying. The code changes the values in Z(:,:,1) as i want them to do, but dimension 2 and 3 are left unchanged... I hope someone can solve my problem. I guess i got the wrong syntax...
Thanks in advance Flo

 採用された回答

Guillaume
Guillaume 2018 年 6 月 28 日

1 投票

mask = X(:, :, 1) == 1 & X(:, :, 2) == 0 & X(:, :, 3) == 0; %fully saturated pure red
mask = repmat(mask, 1, 1, 3); %replicate mask across all 3 colour channels
Z(mask) = X(mask);

4 件のコメント

Flo
Flo 2018 年 6 月 28 日
Thank you for your answer! Your solution works perfectly for me. I will use it.
But it would be great to know why my code isn't working. Any suggestion?
Guillaume
Guillaume 2018 年 6 月 28 日
編集済み: Guillaume 2018 年 6 月 28 日
X(:,:,1) == 1 & X(:,:,2) == 0 & X(:,:,3) == 0
is a 2D logical array, whereas Z is a 3D matrix. While you can use a smaller logical array to index a larger array, matlab fills the missing entry with 0/false. Hence your indexing was equivalent to:
mask = X(:,:,1) == 1 & X(:,:,2) == 0 & X(:,:,3) == 0; %2D logical array
mask3d = cat(3, mask, false(size(mask), false(size(mask))); %expand mask to 3d by filling the rest with false
Z(mask3d) = X(mask3d);
which indeed only copy the first page, the red channel.
Stephen23
Stephen23 2018 年 6 月 28 日
"But it would be great to know why my code isn't working."
Because you used a 2D logical index with a 3D array. Unfortunately there is no simple way to use a 2D mask as you want to, without splitting the array or duplicating the mask. Read this for a short discussion on this topic:
Flo
Flo 2018 年 6 月 28 日
Thx!

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

Flo
2018 年 6 月 28 日

コメント済み:

Flo
2018 年 6 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by