add another column to the end of matrix

조회 수: 8 (최근 30일)
abdul rehman
abdul rehman 2021년 7월 9일
댓글: KSSV 2021년 7월 9일
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
Simon Chan
Simon Chan 2021년 7월 9일
편집: Simon Chan 2021년 7월 9일
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)

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2021년 7월 9일
편집: KSSV 2021년 7월 9일
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
KSSV
KSSV 2021년 7월 9일
What logical error? Check are hand calculations and code are same or not.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by