필터 지우기
필터 지우기

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 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