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
5 次查看(过去 30 天)
显示 更早的评论
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!
采纳的回答
Rik
2019-9-3
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!