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

2 次查看(过去 30 天)
%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

采纳的回答

Voss
Voss 2023-2-3
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 个评论
Les Beckham
Les Beckham 2023-2-3
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

请先登录,再进行评论。

更多回答(1 个)

Les Beckham
Les Beckham 2023-2-3
编辑:Les Beckham 2023-2-3
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 个评论
Renate
Renate 2023-2-3
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 2023-2-3
编辑:Les Beckham 2023-2-3
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by