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

17 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by