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)
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 Comments
Monkey
Monkey on 3 Sep 2019
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.

Sign in to comment.

Accepted Answer

Rik
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.

More Answers (0)

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!