对于if和elseif语句的循环

The*_*gen 0 matlab loops for-loop if-statement

我有一个简单的问题,我正在尝试替换1x60000数组中的值.

这是我的代码,其中Z是1x60000数组:

for i = 1:length(Z)
    if Z(i) == 140
       Z(i) = 1;
    elseif Z(i) == 83
        Z(i) = 2;
    elseif Z(i) == 52
        Z(i) = 3;
    elseif Z(i) == 36
        Z(i) = 4;
    elseif Z(i) == 28
        Z(i) = 5;
    elseif Z(i) == 23
        Z(i) = 6;
    elseif Z(i) == 125
        Z(i) = -1;
    else
       Z = Z(i);
    end
end
Run Code Online (Sandbox Code Playgroud)

数组中的最大值是140.但是,当我运行代码时,我收到此错误:

指数超过矩阵维度.

任何帮助,将不胜感激.

Wol*_*fie 5

你的问题就是这一Z = Z(i)行,你要为数组分配一个值,然后尝试索引下一个循环的单个值.如果您想Z(i)保持不变,只需不要使用else条件.

使用一些逻辑索引可以使整个代码更短(并且更少循环)并且ismember:

% Row 1 values to be replaced in Z by row 2 values
replacements = [140, 83, 52, 36, 28, 23, 125; 
                  1,  2,  3,  4,  5,  6,  -1];
% Get the indices where Z is one of the values to be changed
[~, idx] = ismember(Z, replacements(1,:));
% Use indexing to replace all the values at once
Z(idx~=0) = replacements(2, idx(idx~=0));
Run Code Online (Sandbox Code Playgroud)