Fill a vector whose size is defined during run time

조회 수: 4 (최근 30일)
Karim Sobhi
Karim Sobhi 2015년 2월 14일
댓글: Karim Sobhi 2015년 2월 14일
Hello,
I have to create an vector whose size is not mentioned. The user enters element by element, and he decides when to stop.
I wrote down the code in C++, but I don't know how to write it on Matlab.
answer=1;
size=0;
vector<double>v;
while(answer ==1)
{
cout<<"Enter element number "<<size+1<<": "<<endl;
cin>>temp;
v.push_back(temp);
size=size+1;
cout<<"Do you want to add another number? enter 1 for yes: "
cin>>answer;
}
Can i get some help please.

채택된 답변

Guillaume
Guillaume 2015년 2월 14일
편집: Guillaume 2015년 2월 14일
It's pretty much the same code in matlab. while is while, cin is input, cout is fprintf or disp (or just use input for the prompt), and push_back is v( end+1) = ...
  댓글 수: 4
Guillaume
Guillaume 2015년 2월 14일
temp = input(sprintf('Enter element number %d: ', sz+1));
Note that you shouldn't be using the name size for a variable as that shadows the function of the same name which is very frequently used in matlab.
Karim Sobhi
Karim Sobhi 2015년 2월 14일
perfect thank you !

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by