如何在matlab 2d数组中添加字符','或'+'。 我试过以下方式。
clc
clear all
close all
min=0;
max=1052;
random_int = randi([min max],5,10)
% random_int=[515,586,942,742;353,588,916,436]
% load('Random_Int_x.mat')
% random_int
[m,n]=size(random_int);
for i=1:1:m
allOneString = sprintf('%d,' , random_int(i,:));
allOneString= allOneString(1:end-1)% strip final comma
Str_1(i,:)=allOneString
% allOneString= strjoin(arrayfun(@(x) num2str(x),random_int(i,:),'UniformOutput',false),',');
end
Str_1
输入/矩阵的示例
random_int =
2 9 7 7 9 8 2 5 7 5
6 1 9 9 6 1 9 4 1 0
5 0 8 8 5 6 9 0 4 6
0 9 9 8 7 5 6 3 7 8
8 4 2 0 5 5 1 8 2 6
输出:
Str_1 =
5×19 char array
'2,9,7,7,9,8,2,5,7,5'
'6,1,9,9,6,1,9,4,1,0'
'5,0,8,8,5,6,9,0,4,6'
'0,9,9,8,7,5,6,3,7,8'
'8,4,2,0,5,5,1,8,2,6'
这适用于0-9之间的随机数。但是,如果我将输入放在9以上 - > 10 ..然后matlab抛出矩阵维度错误。
Subscripted assignment dimension mismatch.
Error in Number_with_String (line 14)
Str_1(i,:)=allOneString;
对于高于9的输入:
random_int =
76 96 88 23 26 25 92 5 61 86
87 69 32 36 86 39 46 21 55 69
42 26 56 69 55 97 91 78 76 41
74 74 24 3 46 52 29 70 88 4
7 48 13 69 15 12 79 91 90 24
期待输出:
'76,96,88,23,26,25,92,5,61,86'
'87,69,32,36,86,39,46,21,55,69' ... etc
任何解决此问题的建议......
答案 0 :(得分:2)
这是一种方式:
random_int = randi([0 500],5,10); % example data
y = mat2cell(random_int, ones(1,size(random_int,1)), size(random_int,2)); % split into rows
y = cellfun(@(x) sprintf('%i,', x), y, 'UniformOutput', false); % strings with commas
y = cellfun(@(s) s(1:end-1), y, 'UniformOutput', false); % remove last comma from each
示例结果:
>> y
y =
5×1 cell array
'74,281,294,376,124,203,211,170,242,334'
'488,268,31,84,404,74,205,178,215,20'
'120,242,390,37,113,199,140,375,395,469'
'455,94,115,476,28,20,365,213,181,31'
'130,62,138,421,261,105,114,226,398,90'
答案 1 :(得分:1)
我建议你使用16b发货的字符串。如果需要,可以将结果转换为char或cellstr。
>> min=0; max=1052;
>> random_int = randi([min max],5,10)
random_int =
532 145 857 264 616 793 558 494 327 688
736 157 256 648 578 400 820 12 556 725
938 271 978 498 965 597 983 354 174 787
1010 885 368 370 300 79 136 170 633 474
576 267 207 874 797 56 598 836 276 88
>> str = join(string(random_int),',')
str =
5×1 string array
"532,145,857,264,616,793,558,494,327,688"
"736,157,256,648,578,400,820,12,556,725"
"938,271,978,498,965,597,983,354,174,787"
"1010,885,368,370,300,79,136,170,633,474"
"576,267,207,874,797,56,598,836,276,88"
>> char(str)
ans =
5×39 char array
'532,145,857,264,616,793,558,494,327,688'
'736,157,256,648,578,400,820,12,556,725 '
'938,271,978,498,965,597,983,354,174,787'
'1010,885,368,370,300,79,136,170,633,474'
'576,267,207,874,797,56,598,836,276,88 '
答案 2 :(得分:0)
clc
clear all
close all
min=0;
max=1052;
random_int = randi([min max],200,10);
[m,n]=size(random_int);
for i=1:1:m
allOneString = sprintf('%d,' , random_int(i,:));
allOneString= allOneString(1:end-1); % strip final comma
Str_1{i}=allOneString;
end
Str_1=Str_1'