简体   繁体   中英

How to replace some elements of a matrix by other numbers in MATLAB?

I have a matrix consists of 1000 binary elements like below in Matlab:

M = [011,011,001,010,011,000,010,100,100,...,...]

I want to replace some elements by other numbers: 000 By 000000, 110 By 000001, 001 By 00001, 100 By 0001, 101 By 001, 010 By 01, 011 By 1.

I used this method but doesn't work. What is wrong with it?

for i = 1:1000
    if M(i) == 000
        M(i) = 000000;
    elseif M(i) == 110
         M(i) = 000001;
         elseif M(i) == 001
               M(i) = 00001;
               elseif M(i) == 100
                 M(i) = 0001;   
                 elseif M(i) == 101
                 M(i) = 001; 
                 elseif M(i) == 010
                 M(i) = 01;
    else
         M(i) = 1;
    end
end

Please help me:)

The problem here is in matlab, when you type 000 it means number 0 . If you want to express it as 000 , one way to do that is by using string '000' .

I am going to build a look up chart first.

    Lookup_In  = [  000      110      001    100    101  010  011 ] ;
    Lookup_Out = {'000000','000001','00001','0001','101','01','1' } ;

Then, build a space for the answer, StrOut. M is the original input.

    M = [011,011,001,010,011,000,010,100,100] ;        
    StrOut = repmat({'Unknown'},size(M)) ;

Check if the element in M can find in lookup table Lookup_In .

    [tf, idx] =ismember(M, Lookup_In) ;

Output the final result.

    StrOut(tf) = Lookup_Out(idx(tf))

Then, you will get

     '1'    '1'    '00001'    '01'    '1'    '000000'    '01'    '0001'    '0001'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM