multiply desired indexes in for loop

조회 수: 1 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by