add another column to the end of matrix

8 vues (au cours des 30 derniers jours)
abdul rehman
abdul rehman le 9 Juil 2021
Commenté : KSSV le 9 Juil 2021
I want to add the results of "a" at the end of Carr_veh matrix. I mean in the 6th column the all results of a shouled be. Maybe create another matrix and merge. I am unable to do this.
Code:
x1=randi(5);
y1=randi(5);
time_e=randi([1 5]);
Carr_veh = [rand(100,1),randi([0,1],100,1),randi([5,8],100,1),randi([5,8],100,1),randi([5,12],100,1)]
for i=1:100
a=sqrt(((Carr_veh(i,3))-x1)^2+(Carr_veh(i,4))-y1)^2
end
  1 commentaire
Simon Chan
Simon Chan le 9 Juil 2021
Modifié(e) : Simon Chan le 9 Juil 2021
a is replacing itself in the loop, try replacing the for loop with the following
a = sqrt((Carr_veh(:,3)-x1).^2 + (Carr_veh(:,4)-y1).^2);
another_matrix = horzcat(Carr_veh,a)

Connectez-vous pour commenter.

Réponse acceptée

KSSV
KSSV le 9 Juil 2021
Modifié(e) : KSSV le 9 Juil 2021
x1=randi(5);
y1=randi(5);
time_e=randi([1 5]);
Carr_veh = [rand(100,1),randi([0,1],100,1),randi([5,8],100,1),randi([5,8],100,1),randi([5,12],100,1)] ;
a = zeros(100,1) ; %<--- Initialize a into a column matrix for appending later
for i=1:100
a(i)=sqrt(((Carr_veh(i,3))-x1)^2+(Carr_veh(i,4))-y1)^2 ;
end
iwant = [Carr_veh a] ; % add a as the last column
Actually you need not to use a loop. Just use:
x1=randi(5);
y1=randi(5);
time_e=randi([1 5]);
Carr_veh = [rand(100,1),randi([0,1],100,1),randi([5,8],100,1),randi([5,8],100,1),randi([5,12],100,1)] ;
a = sqrt(((Carr_veh(:,3))-x1).^2+(Carr_veh(:,4))-y1).^2 ;
iwant = [Carr_veh a] ;
  1 commentaire
KSSV
KSSV le 9 Juil 2021
What logical error? Check are hand calculations and code are same or not.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by