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?
Thanks in advance!
  3 个评论
Monkey
Monkey 2019-9-3
Thanks for your hint. I have fixed the problem. I simply converted the string array into numerical arrays containg 0/1 with no space. This is what I need. Thank you.

请先登录,再进行评论。

采纳的回答

Rik
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 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by