Need to define an array
Mostrar comentarios más antiguos
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 comentarios
Stephan
el 26 de Feb. de 2019
sounds like a homework. please provide your attempt so far.
Thomas Holmes
el 26 de Feb. de 2019
madhan ravi
el 27 de Feb. de 2019
What?
Respuestas (2)
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
@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.
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!