how to create matrix c, where first column is vector a, and the last column is vector b without a loop
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
%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
0 commentaires
Réponse acceptée
Voss
le 3 Fév 2023
a = [1;2;3;4;5];
N = 3;
c = a+(0:N)
2 commentaires
Les Beckham
le 3 Fév 2023
Nice!
Expanding on this idea for an arbitrary dimension square result:
N = 10; % desired dimension
a = 1:N;
c = a' + (0:(N-1))
Plus de réponses (1)
Les Beckham
le 3 Fév 2023
Modifié(e) : Les Beckham
le 3 Fév 2023
a = [1;2;3;4;5];
c = [a a+1 a+2 a+3]
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 commentaires
Les Beckham
le 3 Fév 2023
Modifié(e) : Les Beckham
le 3 Fév 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)
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)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!