weird situation while using sprintf to generate a long string with 0 (probability of 0.5) and 1 (probability of 0.5) with space in between two adjacent characters
3 views (last 30 days)
Show older comments
I use the following to generate a length 100 vector:
a = sprintf('%d ', randi([0 1], 1, 100));
When I try length(a), it gives me 200. If I say a(1:10), only the first 5 elements are printed out. However, sometimes "a = sprintf('%d ', randi([0 1], 1, 100));" gives me the correct result.
Can somebody point out how to make the output of "a = sprintf('%d ', randi([0 1], 1, 100));" stable?
You are welcome to refer to a related topic at https://www.mathworks.com/matlabcentral/answers/478585-generating-long-string-with-0-probability-of-0-5-and-1-probability-of-0-5-with-space-in-between?s_tid=ab_new_mlc_ans_email_view#answer_390090.
Thanks in advance!
3 Comments
Accepted Answer
Rik
on 3 Sep 2019
Since this was the solution to the problem, I'll move my comment to the answer section.
Your code creates an array of 0 or 1 and a space. That means for 100 values, your array has length 200. If you select the first 10 elements from the char array, you will see 5 values and 5 spaces.
The observed behavior is therefore expected. If you want to change this you can consider removing the space from the formatspec or use a cell array.
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!