how to create matrix c, where first column is vector a, and the last column is vector b without a loop

2 visualizaciones (últimos 30 días)
%if
a=[1;2;3;4;5];
%and
b=a+3;
%then how can i make a matrix c without a loop, but the result would be like the result of this loop?
for i = 1:5
c(i,:)=a(i,1):b(i,1);
end

Respuesta aceptada

Voss
Voss el 3 de Feb. de 2023
a = [1;2;3;4;5];
N = 3;
c = a+(0:N)
c = 5×4
1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8
  2 comentarios
Les Beckham
Les Beckham el 3 de Feb. de 2023
Nice!
Expanding on this idea for an arbitrary dimension square result:
N = 10; % desired dimension
a = 1:N;
c = a' + (0:(N-1))
c = 10×10
1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 3 4 5 6 7 8 9 10 11 12 4 5 6 7 8 9 10 11 12 13 5 6 7 8 9 10 11 12 13 14 6 7 8 9 10 11 12 13 14 15 7 8 9 10 11 12 13 14 15 16 8 9 10 11 12 13 14 15 16 17 9 10 11 12 13 14 15 16 17 18 10 11 12 13 14 15 16 17 18 19

Iniciar sesión para comentar.

Más respuestas (1)

Les Beckham
Les Beckham el 3 de Feb. de 2023
Editada: Les Beckham el 3 de Feb. de 2023
a = [1;2;3;4;5];
c = [a a+1 a+2 a+3]
c = 5×4
1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8
If you are a beginner in using Matlab, I would suggest taking a couple of hours to go through the free tutorial that can be found here: Matlab Onramp
  2 comentarios
Renate
Renate el 3 de Feb. de 2023
thank you very much!
however, what if i need to extend 3000 rows over 3000 columns? i.e. the rsulting size of the c matrix is not 5X4 but much larger
Les Beckham
Les Beckham el 3 de Feb. de 2023
Editada: Les Beckham el 3 de Feb. de 2023
I can't seem to come up with a way to do that without a loop. Assuming the result is supposed to be square, this should work and seems a bit more clear to me than your loop solution.
N = 10; % desired dimension
a = 1:N;
for i = 1:N
c(i,:) = a + i - 1;
end
disp(c)
1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 3 4 5 6 7 8 9 10 11 12 4 5 6 7 8 9 10 11 12 13 5 6 7 8 9 10 11 12 13 14 6 7 8 9 10 11 12 13 14 15 7 8 9 10 11 12 13 14 15 16 8 9 10 11 12 13 14 15 16 17 9 10 11 12 13 14 15 16 17 18 10 11 12 13 14 15 16 17 18 19
Note that this will create the upper triangular part of the matrix, but I couldn't figure out how to generate the lower half.
c = hankel(1:N)
c = 10×10
1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 0 3 4 5 6 7 8 9 10 0 0 4 5 6 7 8 9 10 0 0 0 5 6 7 8 9 10 0 0 0 0 6 7 8 9 10 0 0 0 0 0 7 8 9 10 0 0 0 0 0 0 8 9 10 0 0 0 0 0 0 0 9 10 0 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 0 0

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by