multiply desired indexes in for loop

2 visualizaciones (últimos 30 días)
Othman Alkandri
Othman Alkandri el 28 de Dic. de 2022
Comentada: Voss el 28 de Dic. de 2022
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)

Respuesta aceptada

Voss
Voss el 28 de Dic. de 2022
Editada: Voss el 28 de Dic. de 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);
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 comentarios
Othman Alkandri
Othman Alkandri el 28 de Dic. de 2022
Thank you
Voss
Voss el 28 de Dic. de 2022
You're welcome!

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 28 de Dic. de 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
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.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by