how to prealloacte and store values in a character array?
31 ビュー (過去 30 日間)
表示 古いコメント
Hi! :)
I want to make a character array consisting of 3 rows and 2 strings and firstly I dont know how I can preallocate it. I also tried to store values in it ( in the first row) using the attached code but failed to do so
best_salt_1 = "ZnBr2";
best_salt_2 = "Format";
combinations_of_best_salts=char(zeros(antall_soner,2))
combinations_of_best_salts(1,1:strlength(best_salt_1))=best_salt_1;
combinations_of_best_salts(1,strlength(best_salt_1):18- strlength(best_salt_2))=best_salt_2;
disp(combinations_of_best_salts)
4 件のコメント
回答 (1 件)
Stephen23
2022 年 8 月 12 日
編集済み: Stephen23
2022 年 8 月 12 日
I am guessing that your strings have different lengths on different loop iterations, in which case it mght not be obvious how to preallocate the array.
Here are two alternative approaches:
N = 7; % number of rows
Character array (preallocated rows, expand columns as required):
M = char(nan(N,0));
for k = 1:N
[S1,S2] = rndstr(k); % random strings
V = sprintf('%s %s',S1,S2);
M(k,1:numel(V)) = V;
end
display(M)
Cell array to collect data, CHAR() after the loop:
C = cell(1,N);
for k = 1:N
[S1,S2] = rndstr(k); % random strings
C{k} = sprintf('%s %s',S1,S2);
end
M = char(C{:})
function [st1,st2] = rndstr(k)
rng(k);
st1 = string(char(randi([33,126],1,randi([3,7]))));
st2 = string(char(randi([33,126],1,randi([3,7]))));
end
参考
カテゴリ
Help Center および File Exchange で Numeric Types についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!