Need to define an array

조회 수: 4 (최근 30일)
Thomas Holmes
Thomas Holmes 2019년 2월 26일
편집: Jan 2019년 2월 27일
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
Thomas Holmes
Thomas Holmes 2019년 2월 26일
T=linspace(1000,100,49)
Fg=zeros(1,98)
for i=1:length(Fg)
if mod(i,2)==0
Fg(i)=Fg(i)
else
Fg(i)=T(i)
end
end
This almost works but it does not replace Fg with the correct value of T.
How can i alter T or the index so that the 1st entry of T will be the first of Fg, then the 2nd entry of T will be the third entry of Fg leaving a zero between them.
madhan ravi
madhan ravi 2019년 2월 27일
What?

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

답변 (2개)

Stephan
Stephan 2019년 2월 27일
편집: Stephan 2019년 2월 27일
Hi,
note that the length of T is 49 - not 98.
The proper way to do this is:
Fg=zeros(1,98);
Fg(1:2:end) = linspace(1000,100,49)
Thats all.
Best regards
Stephan

Jan
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
Stephan
Stephan 2019년 2월 27일
In his question the last element is a zero:
"...[1000, 0, ~990,0.... 100,0]"
Jan
Jan 2019년 2월 27일
@Stephan: You are right. The question is confusing and some feedback of the OP would be nice.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by