multiply desired indexes in for loop
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 28 Dec 2022
Edited: Voss
on 28 Dec 2022
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);
More Answers (1)
Image Analyst
on 28 Dec 2022
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.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!