Remake this without a loop

6 次查看(过去 30 天)
sznailc
sznailc 2021-10-17
编辑: DGM 2021-10-17
How to rewrite this without using a loop?
Basically I want to replace elements in matrix A with 0, that are equal to any of element in vector "vector"
vector = [A(A >= 1.5)].' % Vector, don't change.
for i = 1:vector
A(A == vector(i)) = 0;
end

采纳的回答

the cyclist
the cyclist 2021-10-17
% Pretend data
A = 1 : 7;
vector = [2 3 5];
% Replace values of A with 0, if they are in vector
A(ismember(A,vector)) = 0
A = 1×7
1 0 0 4 0 6 7

更多回答(1 个)

DGM
DGM 2021-10-17
编辑:DGM 2021-10-17
What's wrong with just using the test you're already doing? In the case you've given, the vector is unnecessary.
A(A >= 1.5) = 0;
Or more generally, if you actually need to test against another set,
A = randi(5,5,8)
v = [3 4];
A(ismember(A,v)) = 0;

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by