フィルターのクリア

multiply desired indexes in for loop

3 ビュー (過去 30 日間)
Othman Alkandri
Othman Alkandri 2022 年 12 月 28 日
コメント済み: Voss 2022 年 12 月 28 日
I am trying to multiply the some indxes in my vector, bucuase there is a fctor I need to mutlipy it with the t vector of [ 1, 4,2,4,2,4,2 .........., 1].
  • frist index keep it
  • secound index multiply by 4
  • third index multiply by 2
  • forth index multiply by 4
  • fifth index multiply by 2
  • ..
  • ..
  • ..
  • last index keep it
t = [0.58 , 14.48, 19.91, 21.88, 22.59]
for i = 2:2:(length(t)-1)
A = 4*(t(i))+2*(t(i+1))
end
A = t(1)+A+t(end)

採用された回答

Voss
Voss 2022 年 12 月 28 日
編集済み: Voss 2022 年 12 月 28 日
I think this is what you're going for:
t = [0.58 , 14.48, 19.91, 21.88, 22.59];
Nt = numel(t);
A = zeros(1,Nt);
for i = 2:2:(Nt-1)
A([i, i+1]) = [4*t(i), 2*t(i+1)];
end
A([1, end]) = t([1, end]);
disp(A);
0.5800 57.9200 39.8200 87.5200 22.5900
You can do the same thing like this:
t = [0.58 , 14.48, 19.91, 21.88, 22.59];
f = ones(1,numel(t)); % factors by which to multiply each element of t
f(2:2:end-1) = 4;
f(3:2:end-1) = 2;
A = f.*t;
disp(A);
0.5800 57.9200 39.8200 87.5200 22.5900
  2 件のコメント
Othman Alkandri
Othman Alkandri 2022 年 12 月 28 日
Thank you
Voss
Voss 2022 年 12 月 28 日
You're welcome!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 12 月 28 日
I don't think your for loop does what you asked for in words. Here, try this to multiply a weights vector [1,4,2,4,2,4,......1] by a data vector t:
t = [0.58 , 14.48, 19.91, 21.88, 22.59];
numRepeats = length(t); % Number of times the pair [4,2] repeats.
% Make weights in the form [4,2,4,2,4,2,4,2,......];
weights = repmat([4,2], 1, numRepeats);
% That was too long, so let's crop it so we can multiply the vectors together.
% Also make the first and last element 1.
weights = [1, weights(1:length(t)-2), 1]; % [1,4,2,4,1] for this particular t.
% Now multiply the weights vector by the t vector element-by-element
A = t .* weights
A = 1×5
0.5800 57.9200 39.8200 87.5200 22.5900
Notice all the middle values are either 4 or 2 times the original values, in an alternating fashion.
  1 件のコメント
Othman Alkandri
Othman Alkandri 2022 年 12 月 28 日
Thank you I like the new way you did

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDialog Boxes についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by