How to make a matrix with mixed string and number elements ?
30 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Zahra
el 13 de Jul. de 2022
Comentada: Jon
el 13 de Jul. de 2022
Hi ,
I want to make a Matrix with i rows and 4 colomns. I want to fill it with <X000i> with i a number changing from 1 to N . If the matrix name is A , I want the elemnts to be in the next order :
for i = 1 : N ( if N =10 )
A(1 , 1 ) = <X0001>
A(1 , 2 ) = <X0002>
A(1 , 3 ) = <X0003>
A(1 , 4 ) = <X0004>
A(2 , 1 ) = <X0005>
A(2 , 2 ) = <X0006>
A(2 , 3 ) = <X0007>
A(2 , 4 ) = <X0008>
.............
.............
A(10 , 1 ) = <X0037>
A(10 , 2 ) = <X0038>
A(10 , 3 ) = <X0039>
A(10 , 4 ) = <X0040>
There shoud be only 4 digits after the X .
The hard part is that I don't knwo th code to have eac elemnt of the matrix a micture of number and string.
I woud really appriciate if someone could help me solve my problem .
Thank you .
0 comentarios
Respuesta aceptada
Adam Danz
el 13 de Jul. de 2022
Editada: Adam Danz
el 13 de Jul. de 2022
I think this is your goal
N = 10;
M = 4;
str = compose("x%04d",1:N*M);
A = reshape(str,M,N)'
Note that this is referred to as a string array rather than a matrix. You could also create a cell array of character vectors:
str = compose('x%04d',1:N*M);
A = reshape(str,M,N)'
0 comentarios
Más respuestas (1)
Jon
el 13 de Jul. de 2022
Here's another approach, not so nicely vectorized as @Adam Danz, in which I store the values in a cell array
I hadn't known about the compose function when I wrote up the attached answer. Thanks @Adam Danz for teaching me about the compose function with your answer.
numRows = 10;
numColumns = 4;
% cacluate total number of elements
N = numRows*numColumns;
% generate cell array with elements of form <X000i>
A = cell(numRows,numColumns); % preallocate cell array to hold values
for i = 1:numRows
for j = 1:numColumns
k = sub2ind([numRows,numColumns],i,j);% get linear index
A{i,j} = num2str(k,'<%04d>'); % e.g. '<0035>'
end
end
disp(A)
1 comentario
Jon
el 13 de Jul. de 2022
I guess I forgot that you also wanted the X in your strings, to get this use
A{i,j} = num2str(k,'<X%04d>')
You can also use this in @Adam Danz approach, using the compose function which is nicer because it doesn't need any loops.
Ver también
Categorías
Más información sobre Logical 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!