问题
How can I take part of the vector and fill other part with zero in time efficient way ?
I have a vector ;
A | | A | 0 |
| | | 0 |
| | | 0 |
| | <-------- x -----------> | | <--|
| | | | |
| | | | | data in this region
| | after | | | is not changed
| | | | |
| | operation | | |
| | | | |
| | | | <--|
| | <--------- y -----------> | |
| | | 0 |
| | | 0 |
| | | 0 |
回答1:
u = 1:10;
v = [1:3, 8:10];
u(v) = 0;
Will set the first and last 3 elements to zero. To make it more similar to how you phrased the question:
x = 3;
y = 8;
u = 2:2:20;
v = x:y;
w = 1:length(u);
u(setdiff(w, v)) = 0;
Although you would probably prefer to just do:
u(1:x-1) = 0;
u(y+1:end) = 0;
(The +/-1 is only if you want inclusive range.)
回答2:
Alternatively, you can use logical indexing.
n = 20;
x = rand(n,1); %# sample content
i = 1:n; %# indices
x(~(i>3 & i<n-2)) = 0;
x
x =
0
0
0
0.2435
0.9293
0.3500
0.1966
0.2511
0.6160
0.4733
0.3517
0.8308
0.5853
0.5497
0.9172
0.2858
0.7572
0
0
0
来源:https://stackoverflow.com/questions/10733703/how-to-clear-part-of-vector-in-time-efficient-way