how to prealloacte and store values in a character array?
53 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Stephen23
am 2 Aug. 2022
Bearbeitet: Stephen23
am 2 Aug. 2022
@Muazma Ali: please show the expected output (not a description).
Antworten (1)
Stephen23
am 12 Aug. 2022
Bearbeitet: Stephen23
am 12 Aug. 2022
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
4 Kommentare
Stephen23
am 12 Aug. 2022
Bearbeitet: Stephen23
am 12 Aug. 2022
"what is the input k in your last alternative..?"
k is the loop iterator. You can find the MATLAB documentation for FOR loops here: https://www.mathworks.com/help/matlab/ref/for.html
It is not clear what you mean by "input k": I provided the iterator as an input to my fake-data generator function in order to reset the random number generator, so that both loops would provide exactly the same random numbers and give exactly the same output character matrix. This is completely superfluous and unrelated to the answer, because of course you would use your strings, not my fake data.
"can you try to explain what your last alternative does, line by line.., please?"
C = cell(1,N); % preallocate a cell array to hold character vectors
for k = 1:N % loop N times
[S1,S2] = rndstr(k); % create fake data strings (you use your strings)
C{k} = sprintf('%s %s',S1,S2); % create character vector and store in cell array
end %
M = char(C{:}) % join all character vectors into one character matrix
Note that CHAR() automatically pads the character vectors with spaces, in order to create the matrix.
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!