# How to assign values to matrix

11 Ansichten (letzte 30 Tage)
Jacob Bunyamin am 10 Feb. 2023
Kommentiert: Walter Roberson am 10 Feb. 2023
Good afternoon,
I have a matrix consisted of binary values (1 and 0), in which I want to assign the value of 1 to the 0 and 2 to 1 (for multiplication purposes). Is there a function to work on this problem?
Thanks,
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
KSSV am 10 Feb. 2023
Question is not clear.....can you show us an example?

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Tushar Behera am 10 Feb. 2023
Hi jacob,
I assume you want to convert your matrix containing binary values such that 0 will be 1 and 1 will be 2.
This can be acheived in a multitude of ways. One such way will be to add each and every element of the matrix with 1. For example:
matrix = [0 1 0; 1 0 1];
b=matrix+1
%%
b =
1 2 1
2 1 2
Also, you can change the specific values in a matrix by using an element-wise comparison and assignment. Here's an example:
matrix = [0 1 0; 1 0 1];
result = (matrix == 0) + (matrix == 1) * 2
%%
result =
1 2 1
2 1 2
The resulting matrix result will have the values 1 and 2, as you required. This works by creating two logical arrays, one where the elements of matrix are equal to 0, and one where they are equal to 1. These logical arrays are then cast to numeric arrays, with zeros becoming ones and ones becoming twos. The two arrays are then added together to obtain the final result.
Regards,
Tushar
##### 3 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Jacob Bunyamin am 10 Feb. 2023
Hi Tushar,
Another question, I trie dto multiply my matrix , one is uint8 and one is uint 16 files. I could not use mtimes function because both are integers,
Do you know how to fix this issue?
Thanks
Walter Roberson am 10 Feb. 2023
uint16(TheUint8Matrix) .* TheUint16Matrix

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Walter Roberson am 10 Feb. 2023
YourMatrix + 1
satisfies that mapping
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by