add another column to the end of matrix

8 views (last 30 days)
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 Comment
Simon Chan
Simon Chan on 9 Jul 2021
Edited: Simon Chan on 9 Jul 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)

Sign in to comment.

Accepted Answer

KSSV
KSSV on 9 Jul 2021
Edited: KSSV on 9 Jul 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 Comment
KSSV
KSSV on 9 Jul 2021
What logical error? Check are hand calculations and code are same or not.

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!