Make first and last element of array 0

35 views (last 30 days)
Sarah Gomez
Sarah Gomez on 28 Feb 2022
Commented: Stephen23 on 21 Mar 2022
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 Comment
Stephen23
Stephen23 on 21 Mar 2022
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

Sign in to comment.

Answers (2)

Voss
Voss on 28 Feb 2022
Edited: Voss on 28 Feb 2022
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 on 28 Feb 2022
Edited: Arif Hoq on 28 Feb 2022
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!