Need to define an array
조회 수: 4 (최근 30일)
이전 댓글 표시
I need an array that has 98 entries. the first value is 1000 and the second to last is 100. the values inbetween vary linearly but alternate with zeros.
[1000, 0, ~990,0.... 100,0]
댓글 수: 3
답변 (2개)
Jan
2019년 2월 27일
편집: Jan
2019년 2월 27일
@Thomas: The problem is still unclear.
"the first value is 1000 and the second to last is 100" - this means:
R = [1000, repmat(100, 1, 97)]
"the values inbetween vary linearly but alternate with zeros" - this is not clear: inbetween what?
The output should have 98 elements, while the first and the last is non-zero and the others are zero. This is not possible, because you need an odd number of elements for this.
You have shown some effort. So although I assume it is a homework, it is worth to assist you. Maybe all you want can be done in a single line:
Result(1:2:97) = linspace(1000, 100, 49);
But te result has 97 elements. There is no way for alternating zeros and non-zeros with leading and trailing non-zero and and even number of elements. Maybe with a trailing 0 (see Stephan's comment) pre-allocate the output at first:
Result = zeros(1, 98);
Or with your loop:
T = linspace(1000, 100, 49)
Fg = zeros(1, 98);
for k = 1:length(T) % Not length(Fg)
Fg(k * 2 - 1) = T(k);
end
Again, the last element is 0 then.
댓글 수: 2
Jan
2019년 2월 27일
@Stephan: You are right. The question is confusing and some feedback of the OP would be nice.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!