How to create a new vector from another vector which contains the value times the index

2 visualizaciones (últimos 30 días)
Hello, I'm new to programming and I would like to create a new vector2 from another vector1 which contains i*vector1(i).
Let's say I have
vector1 = [5,4,3,1]
So vector2 should look like this: vector2 = [1,1,1,1,1,2,2,2,2,3,3,3,4]
I tried to use a nested for-loop but I can't get the result right.
vector1 = [5,4,3,1]
vector2 = []
for i = 1:length(vector1)
for j = 1:vector1(i)
Vektor2 = [j*i]
end
end
I would be thankfull for any suggestions.
  4 comentarios
Romechelle
Romechelle el 28 de Oct. de 2023
p=[1 2 3 4 5 6 7 8 9 10 -1 -2]
q=[4 1 3 -2 1 -8 4 -11 9 6 13 -4]
create a new row vector s that is made of the elements of p that are less than or equal to the corresponding elements of q
Jan
Jan el 9 de Nov. de 2023
@Romechelle: Please do not post a new question in the section for comments of another question. Open a new thread instead and delete this comment. Thanks.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 24 de Mzo. de 2021
Editada: Jan el 24 de Mzo. de 2021
v1 = [5,4,3,1];
v2 = [];
for i = 1:length(v1)
for j = 1:v1(i)
v2 = [v2, i];
end
end
You can omit the inner loop for more matlab'ish code:
v2 = [];
for i = 1:length(v1)
v2 = [v2, repmat(i, 1, v1(i))];
end
An efficient method would be:
vector2 = repelem(1:numel(vector1), vector1)
or in old Matlab versions before repelem was introduced:
v1 = [5,4,3,1];
ind = zeros(1, sum(v1));
ind(cumsum([1, v1(1:end-1)])) = 1;
v2 = cumsum(ind)
  2 comentarios
Jan
Jan el 24 de Mzo. de 2021
You are welcome. I know, that it is not useful to solve otherones homework. But if you understand the 3 different approachs, you have learned something important about Matlab also.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by