Make first and last element of array 0

19 次查看(过去 30 天)
N = 12*0.5;
TAU_max = 15;
for i = 1:N
TAU(i,:) = i*(TAU_max/N);
end
I have a little loop here that creates a column vector with my dummy variables. But how I do make it so the (1,1) and (1:N) elements are 0 while still preserving my original values?
  1 个评论
Stephen23
Stephen23 2022-3-21
You don't need a loop:
N = 12*0.5;
TAU_max = 15;
TAU = (1:N)*(TAU_max/N)
TAU = 1×6
2.5000 5.0000 7.5000 10.0000 12.5000 15.0000

请先登录,再进行评论。

回答(2 个)

Voss
Voss 2022-2-28
编辑:Voss 2022-2-28
Pre-allocate TAU as a vector of zeros, then just set elements 2 through N-1:
N = 12*0.5;
TAU_max = 15;
TAU = zeros(N,1); % pre-allocate
for i = 2:N-1
TAU(i,:) = i*TAU_max/N;
end
disp(TAU);
0 5.0000 7.5000 10.0000 12.5000 0
Alternatively, set all elements and afterward set elements 1 and N to zero:
N = 12*0.5;
TAU_max = 15;
TAU = zeros(N,1);
for i = 1:N
TAU(i,:) = i*TAU_max/N;
end
TAU([1 N],:) = 0;
disp(TAU);
0 5.0000 7.5000 10.0000 12.5000 0

Arif Hoq
Arif Hoq 2022-2-28
编辑:Arif Hoq 2022-2-28
try this:
N = 12*0.5;
TAU_max = 15;
for i = 1:N
TAU(i,:) = i*(TAU_max/N);
TAU([1 N],:)=0;
end
disp(TAU)
0 5.0000 7.5000 10.0000 12.5000 0

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by