Make first and last element of array 0

47 ビュー (過去 30 日間)
Sarah Gomez
Sarah Gomez 2022 年 2 月 28 日
コメント済み: Stephen23 2022 年 3 月 21 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by