Need to define an array

2 Ansichten (letzte 30 Tage)
Thomas Holmes
Thomas Holmes am 26 Feb. 2019
Bearbeitet: Jan am 27 Feb. 2019
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 Kommentare
Thomas Holmes
Thomas Holmes am 26 Feb. 2019
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 am 27 Feb. 2019
What?

Melden Sie sich an, um zu kommentieren.

Antworten (2)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by