Replace values in matrix with other values

后端 未结 4 2048
情歌与酒
情歌与酒 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
    

提交回复
热议问题