开发者

Complicated If loops

Does anybody know if there is a simple way to make this kind of if-loop:

If a or b (or more of them) equal 1, then the new value of 开发者_开发技巧ONLY those variables that are true changes to e.g. 5?!


Try this, if I understood your problem correctly

newValue = 5;
valueToFind = 1;
vector = [2 3 4 6 1 3 2 1 3];

vector(vector==valueToFind) = newValue;

Update (to respond to your comment below):

There's is no one right way to do it, but I would probably make a "table" of values to look for and what to reapace with their new counterparts. For example,

valuesTable = [1 3 4 6 9;... %#old values
               2 0 5 7 0];   %#new values

You could then go through them as follows:

vector = [2 3 4 6 1 3 2 1 3];

valuesTable = [1 3 4 6 9;... %#old values
               2 0 5 7 0];   %#new values

N = size(valuesTable,2);     %#count indices to go through

for n = 1:N
    old = valuesTable(1,n);  %#get current old value
    new = valuesTable(2,n);  %#get corresp. new value

    vector(vector==old) = new; %#replace the values
end

There could be other approaches rather than my "table" approach, but I find it clear, palpable and easy to read.


To extend Phonon's answer to the case where you have several values to find, use ismember.

newValue = 5;
valuesToFind = [1 3];
vector = [2 3 4 6 1 3 2 1 3];

vector(ismember(vector, valuesToFind)) = newValue
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜