Borrar filtros
Borrar filtros

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

17 visualizaciones (últimos 30 días)
Sim
Sim el 13 de Jun. de 2023
Editada: Dyuman Joshi el 13 de Jun. de 2023
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 comentarios
Stephen23
Stephen23 el 13 de Jun. de 2023
"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 el 13 de Jun. de 2023
@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

Iniciar sesión para comentar.

Respuesta aceptada

Dyuman Joshi
Dyuman Joshi el 13 de Jun. de 2023
Editada: Dyuman Joshi el 13 de Jun. de 2023
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

Más respuestas (1)

Sim
Sim el 13 de Jun. de 2023
Editada: Sim el 13 de Jun. de 2023
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

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by