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

3 ビュー (過去 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
Renate
Renate 2023 年 2 月 5 日
great! thank you both very much!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by