MATLAB:从数组中删除特定元素
MATLAB: Remove specific elements from array
问题1:我有一个1x15的数组,由正整数和负整数组成。我希望实现一个 MATLAB 代码,它保留所有正整数并跳过具有负内容的单元格。
我试过以下方法:
X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2];
[r c] = size(X);
for i=1:r
for j=1:c
if X(i,j)<0
X(i,j)=X(i,j+1)
end
end
end
输出应该是:
X_new = [1 2 3 4 5 1 4 6 8 9 2 4]
我该怎么做?
问题二:
X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2]
Y = [5 3 8 9 4 5 6 7 4 7 9 5 2 1 4]
来自问题 1,
X_new = [1 2 3 4 5 1 4 6 8 9 2 4]
我需要删除Y
中的相应值,以便:
Y_new = [5 3 8 9 4 6 4 7 9 5 2 1]
如何执行此操作?
在 MATLAB 中,操作数组和矩阵比 for 循环解决方案容易得多,
在你的任务中,可以在数组中找到并删除负值,简单地说,如下:
Idx_neg = X < 0; % finding X indices corresponding to negative elements
X ( Idx_neg ) = []; % removing elements using [] operator
Y ( Idx_neg ) = []; % removing corresponding elements in Y array
问题1:我有一个1x15的数组,由正整数和负整数组成。我希望实现一个 MATLAB 代码,它保留所有正整数并跳过具有负内容的单元格。
我试过以下方法:
X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2];
[r c] = size(X);
for i=1:r
for j=1:c
if X(i,j)<0
X(i,j)=X(i,j+1)
end
end
end
输出应该是:
X_new = [1 2 3 4 5 1 4 6 8 9 2 4]
我该怎么做?
问题二:
X = [1 2 3 4 5 -10 1 -5 4 6 8 9 2 4 -2]
Y = [5 3 8 9 4 5 6 7 4 7 9 5 2 1 4]
来自问题 1,
X_new = [1 2 3 4 5 1 4 6 8 9 2 4]
我需要删除Y
中的相应值,以便:
Y_new = [5 3 8 9 4 6 4 7 9 5 2 1]
如何执行此操作?
在 MATLAB 中,操作数组和矩阵比 for 循环解决方案容易得多, 在你的任务中,可以在数组中找到并删除负值,简单地说,如下:
Idx_neg = X < 0; % finding X indices corresponding to negative elements
X ( Idx_neg ) = []; % removing elements using [] operator
Y ( Idx_neg ) = []; % removing corresponding elements in Y array