如何以时间有效的方式参与矢量并用零填充其他部分?
我有一个矢量;
A | | A | 0 |
| | | 0 |
| | | 0 |
| | <-------- x -----------> | | <--|
| | | | |
| | | | | data in this region
| | after | | | is not changed
| | | | |
| | operation | | |
| | | | |
| | | | <--|
| | <--------- y -----------> | |
| | | 0 |
| | | 0 |
| | | 0 |
答案 0 :(得分:7)
u = 1:10;
v = [1:3, 8:10];
u(v) = 0;
将第一个和最后三个元素设置为零。为了使它更像你提出问题的方式:
x = 3;
y = 8;
u = 2:2:20;
v = x:y;
w = 1:length(u);
u(setdiff(w, v)) = 0;
虽然您可能更愿意这样做:
u(1:x-1) = 0;
u(y+1:end) = 0;
(仅当你想要包含范围时才+/- 1。)
答案 1 :(得分:4)
或者,您可以使用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