フィルターのクリア

A compact way to assign values of a matrix to another matrix

17 ビュー (過去 30 日間)
Sim
Sim 2023 年 6 月 13 日
編集済み: Dyuman Joshi 2023 年 6 月 13 日
How to assign the values of matrix "x" to the matrix "y" in a, possibly, single line of code?
% Input
x = [3 2 2; 4 5 3; 6 5 4; 4 6 5; 5 6 6; 6 6 7];
y = logical([0 0 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1]);
% Desired Output
>> y
Invalid use of operator.
y =
0 0 0
3 2 2
4 5 3
6 5 4
4 6 5
5 6 6
6 6 7
% My attempt
>> y(find(y))=x
y =
7×3 logical array
0 0 0
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
  4 件のコメント
Stephen23
Stephen23 2023 年 6 月 13 日
"How to assign the values of matrix "x" to the matrix "y" in a, possibly, single line of code?"
Given that matrix y is of logical type, all non-zero values will be cast into TRUE values. Is that what you want?
Sim
Sim 2023 年 6 月 13 日
@Stephen23, thanks for the comment!! No, I do not want that all non-zero values will be cast into true values. I would like this (I just converted the logical matrix into a numerical matrix):
x = [3 2 2; 4 5 3; 6 5 4; 4 6 5; 5 6 6; 6 6 7];
y = ([0 0 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1]);
y(y~=0)=x
y = 7×3
0 0 0 3 2 2 4 5 3 6 5 4 4 6 5 5 6 6 6 6 7

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

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 6 月 13 日
編集済み: Dyuman Joshi 2023 年 6 月 13 日
Since y is a logical array, any values assigned to it will be converted to corresponding logical value.
Convert y into double and then assign -
%Modified x, x(1,2) is 0.
x = [3 0 2; 4 5 3; 6 5 4; 4 6 5; 5 6 6; 6 6 7];
y = logical([0 0 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1]);
%temporary variable
y1 = y;
%assigning to logical
%You can see how assignment is done to logical array
%0 is assigned as 0 and any other value is 1
y1(y1) = x
y1 = 7×3 logical array
0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
%convert to double
z = double(y)
z = 7×3
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
%and assign
z(y)=x
z = 7×3
0 0 0 3 0 2 4 5 3 6 5 4 4 6 5 5 6 6 6 6 7

その他の回答 (1 件)

Sim
Sim 2023 年 6 月 13 日
編集済み: Sim 2023 年 6 月 13 日
Sorry, stupid question... I had a logical matrix "y" and I got what I wanted, just by assigning a numerical array instead of a logical one:
x = [3 2 2; 4 5 3; 6 5 4; 4 6 5; 5 6 6; 6 6 7];
y = ([0 0 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1]);
y(y~=0)=x
y = 7×3
0 0 0 3 2 2 4 5 3 6 5 4 4 6 5 5 6 6 6 6 7

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by