Effacer les filtres
Effacer les filtres

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

17 vues (au cours des 30 derniers jours)
Sim
Sim le 13 Juin 2023
Modifié(e) : Dyuman Joshi le 13 Juin 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 commentaires
Stephen23
Stephen23 le 13 Juin 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 le 13 Juin 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

Connectez-vous pour commenter.

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 13 Juin 2023
Modifié(e) : Dyuman Joshi le 13 Juin 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

Plus de réponses (1)

Sim
Sim le 13 Juin 2023
Modifié(e) : Sim le 13 Juin 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

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by