How to make a matrix with mixed string and number elements ?
조회 수: 22 (최근 30일)
이전 댓글 표시
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
채택된 답변
Adam Danz
2022년 7월 13일
편집: Adam Danz
2022년 7월 13일
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
추가 답변 (1개)
Jon
2022년 7월 13일
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
Jon
2022년 7월 13일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!