Borrar filtros
Borrar filtros

How To change Diagonal Elements with a string in matrix using FOR loop or other preferred method?

19 visualizaciones (últimos 30 días)
the result is to have a square matrix with a string e.g. "A" as diagonal elements using FOR LOOP
example:
M =
A 0 0 0 0
0 A 0 0 0
0 0 A 0 0
0 0 0 A 0
0 0 0 0 A
or How can I Print my name like ALEX diagonally
example;
M =
A 0 0 0
0 L 0 0
0 0 E 0
0 0 0 X
Here is My code that gives a specific number I assigned to variable in loop; however when that number is replaced with string it results NAN value as Diagonal elements.
clc
clear
clear all
m=5;
n=5;
a=zeros(m,n);
for i=1:m
for j=1:n
if i==j
a(i,j)= 5 ;
else
a(i,j)=0;
end
end
end
disp(a)
5 0 0 0 0 0 5 0 0 0 0 0 5 0 0 0 0 0 5 0 0 0 0 0 5
clc
clear
clear all
m=5;
n=5;
a=zeros(m,n);
for i=1:m
for j=1:n
if i==j
a(i,j)= "A" ;
else
a(i,j)=0;
end
end
end
disp(a)
NaN 0 0 0 0 0 NaN 0 0 0 0 0 NaN 0 0 0 0 0 NaN 0 0 0 0 0 NaN
  1 comentario
Turlough Hughes
Turlough Hughes el 24 de Sept. de 2022
You can't mix characters or string values into an array of type double like that. On the otherhand, you can atleast represent numbers in a string array. Seeing as this is an exercise, I'm just going to nudge you towards a solution. Try starting with the following:
a = string(zeros(5))
a = 5×5 string array
"0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"

Iniciar sesión para comentar.

Respuestas (1)

David Hill
David Hill el 24 de Sept. de 2022
a='ALEX';
b=diag(double(a));
b(b==0)=48;
string(char(b))
ans = 4×1 string array
"A000" "0L00" "00E0" "000X"
char(b)
ans = 4×4 char array
'A000' '0L00' '00E0' '000X'

Categorías

Más información sobre Loops and Conditional Statements 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