Replace values in matrix with other values

后端 未结 4 2037
情歌与酒
情歌与酒 2020-12-10 13:16

I have a matrix with integers and I need to replace all appearances of 2 with -5. What is the most efficient way to do it? I made it the way below, but I am sure there is mo

相关标签:
4条回答
  • 2020-12-10 13:25

    Here's a trivial, unoptimised, probably slow implementation of changem from the Mapping Toolbox.

    function mapout = changem(Z, newcode, oldcode)
    % Idential to the Mapping Toolbox's changem
    % Note the weird order: newcode, oldcode. I left it unchanged from Matlab.
        if numel(newcode) ~= numel(oldcode)
            error('newcode and oldcode must be equal length');
        end
    
        mapout = Z;
    
        for ii = 1:numel(oldcode)
            mapout(Z == oldcode(ii)) = newcode(ii);
        end
    end
    
    0 讨论(0)
  • 2020-12-10 13:30

    The Martin B's method is good if you are changing values in vector. However, to use it in matrix you need to get linear indices.

    The easiest solution I found is to use changem function. Very easy to use:

    mapout = changem(Z,newcode,oldcode) In your case: newA = changem(a, 5, -2)

    More info: http://www.mathworks.com/help/map/ref/changem.html

    0 讨论(0)
  • 2020-12-10 13:33

    Try this:

    a(a==2) = -5;
    

    The somewhat longer version would be

    ind_plain = find(a == 2);
    a(ind_plain) = -5;
    

    In other words, you can index a matrix directly using linear indexes, no need to convert them using ind2sub -- very useful! But as demonstrated above, you can get even shorter if you index the matrix using a boolean matrix.

    By the way, you should put semicolons after your statements if (as is usually the case) you're not interested in getting the result of the statement dumped out to the console.

    0 讨论(0)
  • 2020-12-10 13:39

    find is not needed in this case. Use logical indexing instead:

    a(a == 2) = -5
    

    In case of searching whether a matrix is equal to inf you should use

    a(isinf(a)) = -5

    The general case is:

    Mat(boolMask) = val

    where Mat is your matrix, boolMask is another matrix of logical values, and val is the assignment value

    0 讨论(0)
提交回复
热议问题