Hey guys,
I am having a trouble now.
I would like to create a vector, a2 = 1.0000 0.5000 0.3333 0.2500 0.2000, but I can only have "exactly one line of code".
For example, the code xx = 1 : 6 is acceptable; the code xx = [1, 2, 3, 4, 5, 6] is not.
In addition, loop is not the right choice.
Could someone help me about it?Thanks a lot!

 채택된 답변

Star Strider
Star Strider 2015년 9월 27일

0 개 추천

I would generate ‘a2’ simply as:
a2 = 1./[1:6]
a2 =
1 0.5 0.33333 0.25 0.2 0.16667
One line of code, as required.

댓글 수: 2

Tiankang Xie
Tiankang Xie 2015년 9월 28일
Thank you so much that's really awesome!
Star Strider
Star Strider 2015년 9월 28일
My pleasure!
The sincerest form of appreciation here on MATLAB Answers is to Accept the Answer that most closely solves your problem.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 9월 27일

0 개 추천

The line of code
xx = [1, 2, 3, 4, 5, 6]
is exactly one line of code. Why do you insist it's not?
My solution to your question is to simply do this:
a2 = [1.0000 0.5000 0.3333 0.2500 0.2000]
Note, it is definitely one single line of code.

댓글 수: 5

Alternatively, another way is
a2 = ones(1,5) ./ [1:5]
However if that's your homework, now you can't use it because that would be plagiarizing, and you'll have to find another solution. But I'm sure it's not your homework or else you definitely would have tagged it as homework.
Tiankang Xie
Tiankang Xie 2015년 9월 27일
I think I might need to use functions or special notations to represent the vector instead of just typing the vector. Like using functions like"ones, zeros, eye"
You did see the call to ones() I used in the comment, didn't you? Why doesn't that suffice? Why does it even matter how you create the vector? I mean, who cares how you get it as long as you get it?
WAT
WAT 2015년 9월 28일
My best guess is that he or she was looking for a form that is easily generalizable to create an arbitrarily long vector. That's obviously far different from saying "exactly one line of code" though.
If they have an integer n, then the OP can make it general by doing either of these lines:
a2 = ones(1,n) ./ [1:n]
a2 = 1 ./ [1:n]; % Parentheses also work (1:n)
whichever they prefer.

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

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

태그

질문:

2015년 9월 27일

댓글:

2015년 9월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by