multiply desired indexes in for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
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)
댓글 수: 0
채택된 답변
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);
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);
추가 답변 (1개)
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
Notice all the middle values are either 4 or 2 times the original values, in an alternating fashion.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!