how to add colmun to vector

조회 수: 1 (최근 30일)
tomer polsky
tomer polsky 2018년 1월 4일
답변: Guillaume 2018년 1월 4일
hello how can i add to my colmn vector using for loop ?
for exmaple i have this vector [0;0] and i want it to grow by one and keep adating like this for exmaple [0 1;0 1] and then [0 1 2; 0 1 2] and then [0 1 2 3; 0 1 2 3 ] and so on
  댓글 수: 1
Guillaume
Guillaume 2018년 1월 4일
Note that growing arrays in a loop is not recommended. It adversely affects performance. Preallocation and indexing is recommended instead.

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

답변 (3개)

Torsten
Torsten 2018년 1월 4일
help horzcat
Best wishes
Torsten.
  댓글 수: 4
tomer polsky
tomer polsky 2018년 1월 4일
thank you very much is there any other way without using horzcat command ?
Torsten
Torsten 2018년 1월 4일
mat = [mat,i*id];
Best wishes
Torsten.

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


tomer polsky
tomer polsky 2018년 1월 4일
편집: Guillaume 2018년 1월 4일
clc;
clear all;
x=[0;0]
for i=1:5
x(:,i)=i
end
your wat is too complicated ,here is the way i found
  댓글 수: 1
Guillaume
Guillaume 2018년 1월 4일
Torsten's way may be too complicated but it certainly performs better than the above. In particular, in the first step of the loop, the above replaces
x = [0;0]
by
x = [1;1]
The next steps of the loop do indeed grow x (not recommended) so the end result is:
x = [1 2 3 4 5; 1 2 3 4 5]
not
x = [0 1 2 3 4;0 1 2 3 4] %or maybe [0 1 2 3 4 5;0 1 2 3 4 5]
as was requested

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


Guillaume
Guillaume 2018년 1월 4일
And the proper way is to use preallocation instead of growing the array:
numsteps = 5; %and not using hardcoded ends for loops
x = zeros(2, numsteps);
for i = 1:numsteps
x(:, i) = i-1;
end

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by