0

MATLAB stores 00 and 01 as 0 and 1 respectively. How can I make MATLAB store 00 as 00 and 01 as 01 instead of 0 and 1 only...here is my code.. I am talking about the statements with <-- only..In fact I want to input the result as initial population(chromosome) to a genetic algorithm.

function [x]=abc()
r=randi([0 3],1,20);
for i=1:20 
       if r(i)==0
            x(i)=00; %// <--
        elseif r(i)==1 
            x(i)=01; %// <--
        elseif r(i)==2
           x(i)=10;
        elseif r(i)==3 
            ex(i)=11;
        end 
    end
end
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • 1
    How about storing two columns in a matrix? – Dev-iL Dec 04 '14 at 08:33
  • 1
    Or else as a string. – Dan Dec 04 '14 at 08:36
  • 1
    What do you mean by storing `00`? `0` and `00` is the same integer. – Leonid Beschastny Dec 04 '14 at 08:37
  • @Dev-iL can u please share code for this as i am totally new to matlab. – Tariq Islam Dec 04 '14 at 08:39
  • Ignoring the fact that a loop may not be the best way to go here... Here are just a couple of options: **1)** define x as a cell `x={}`, and then you do `x{i} = [0,0]` (or `[0,1]` etc.); **2)** preallocate `x` as an `i-by-2` matrix (ex. `x(i,2)=0;` and in the `if` structure you just write `x(i,:) = [0,0]` etc. – Dev-iL Dec 04 '14 at 08:45

1 Answers1

4

It looks like you want to store the binary representation of your numbers, so you can use the function dec2bin

and the best thing, you don't even need a loop ;)

r=randi([0 3],1,20);
x = dec2bin(r,2) ;

>> x
x =
10
00
11
11
10
11
10
01
...
Hoki
  • 11,637
  • 1
  • 24
  • 43
  • thanks for the code...this is really useful for me.....i have one more question....Is is possible (in "randi()" function) to have more number of 3's compared to 2's...similarly more number of 2's compared to 1's and so on...i mean can we assign probabilities to them...e.g. probabilities like 0.4 to 3, 0.3 to 2, 0.2 to 1 and 0.1 to 0. – Tariq Islam Dec 04 '14 at 09:58
  • Thanks for the feedback. Nice to know when we've been useful. As for assigning weights to the probability of occurrences, look at [this answer](http://stackoverflow.com/questions/2977497/weighted-random-numbers-in-matlab/2977602#2977602) – Hoki Dec 04 '14 at 10:09