create space between string output in matlab

Status
Not open for further replies.

rameshrai

Member
hello,

does anybody know how to create space between string output in matlab?

for example:

halt(k) = 'A';
....
halt(k) = 'B';

disp(['Output: ', halt]);

The output is
output: ABAAAABBAABABAAABAAB

I want to create space between A and B in the output, they appear attached together

how to create space between them?

thanks
 
Post your actual code; there are typo's in what you provided. Also show what you actually want as output.
 
Maybe the easiest solution is to output every letter one by one in a loop. Then you can output space after every letter.
 
its looks so easy but difficult
It is not difficult. I've listed a couple of methods to do it. The first uses a for loop, as suggested by misterT. The second (or third) uses strrep to replace parts of the halt string). This means that you only need to use a single method in each code block to get the described output. Using all lines in a code block will get a duplicated output.

For inserting a space between occurrences of A & B (which seems to be what you asked for):
Code:
>> for i=1:length(halt)-1, if halt(i)=='A' && halt(i+1)=='B', fprintf('A '); else fprintf('%c', halt(i)); end; end; fprintf('%c\n', halt(end));
>> disp(strrep(halt,'AB','A B'))
Output: A BAAAA BBAA BA BAAA BAA B (repeated on two lines)

If you wanted spaces between A & B and B & A, then
Code:
>> for i=1:length(halt)-1, if (halt(i)=='A' && halt(i+1)=='B') || (halt(i)=='B' && halt(i+1)=='A'), fprintf('%c ',halt(i)); else fprintf('%c', halt(i)); end; end; fprintf('%c\n', halt(end));
>> disp(strrep(strrep(halt,'AB','A B'),'BA','B A')
Output: A B AAAA BB AA B A B AAA B AA B (repeated on two lines)

Or if you actually just wanted a space between all characters,
Code:
>> for i=1:length(halt)-1, fprintf('%c ',halt(i)); end; fprintf('%c\n', halt(end));
>> str = [halt; halt*0+' ']; disp(str(:)');
>> disp(strrep(strrep(halt,'A','A '),'B','B ')
Output: A B A A A A B B A A B A B A A A B A A B (repeated on three lines)
 
Last edited:
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…