The problem I have is that it only works partially, but what can I add to make it work?
A2 = [20 4 6 8 5];
A3 = [10 2 3 4 6];
Str=[];
formatSpec = 'P%d (%d,%d)';
for i=1:length(A2)
str = char(sprintf (formatSpec, i, A2(i),A3(i)));
Str=[Str;str];
end
set(handles.text2,'string',Str);
You are not concatenating strings but char-arrays. Thinking it this way, it already answers your question: If you have a two-digit number, the char-array is one element longer than the char-array of a single-digit number... and you cannot concatenate two arrays of different size vertically.
The solution is fairly simple: use actual strings (introduced somewhere around R2016a). Strings are indicated with
""instead of'', which are chars. So replace yourcharwithstringand it works fine. (Even better: provide theformatSpecas""-string and itsprintf()will return a string right away)Side note:
BTW, you should always allocate memory if your are looping. That is why the
Strhas an orange squiggly underline. This is because MATLAB stores arrays in RAM contiguously and has to copy it to a larger section it it outgrows the current one. So instead ofStr=[], writeStr = strings(length(A2),1), and indexStr(i) = ...in the loop.Personally, I like
num2strmore thatsprintfbut I cannot give a good reason for this, except for that it also works without providing a format.