How to trim down data in an array

Hi,
I have a column vector containing 1000 element.
I really need to reduce the size of the vector to 100 to be able to use it further in my program.
The reduced data must contain the first and last element of the original vector.
My current code is shown below. It does not capture the last element.
Thanks for your help.
a = 1;
b = 200;
A = (b-a).*rand(1000,1) + a;
%
tt = floor(length(A)/10);
if tt == 0
tt = 1;
end
red_A = A(1:tt:end)

4 comentarios

Ünal Dikmen
Ünal Dikmen el 8 de Jul. de 2025
you can do it simply as below:
...
red_A = A(1:tt:end-1) + A(end);
a = 1;
b = 200;
A = (b-a).*rand(1000,1) + a;
%
tt = floor(length(A)/10)
tt = 100
red_A = A(1:tt:end-1);
size(red_A)
ans = 1×2
10 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A(end) added to red_A will produce a vector of the same length as red_A, so A(1:tt:end-1) + A(end) would be a vector of length 10. But the task was to produce a vector of length 100.
Ünal Dikmen
Ünal Dikmen el 8 de Jul. de 2025
Editada: Walter Roberson el 8 de Jul. de 2025
yes, you are right. I thought you wanted to get especially the last element in this vector. if you want to get a constant number of elements (100 as in this example) in a vector, you can use code below:
noel = 100;
npts = numel(A);
interval = ceil(npts-1)/noel;
red_A=A(1:interval:npts);
using this code you can get the number of elements noel in the vector.
a = 1;
b = 200;
A = (b-a).*rand(1000,1) + a;
noel = 100;
npts = numel(A);
interval = ceil(npts-1)/noel;
red_A=A(1:interval:npts);
Warning: Integer operands are required for colon operator when used as index.
size(red_A)
ans = 1×2
101 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Your code has the warning about non-integer increment, and produces a vector that is 1 element too long
red_A(end) == A(end)
ans = logical
1
But at least the last element appears to be correct.

Iniciar sesión para comentar.

 Respuesta aceptada

Walter Roberson
Walter Roberson el 10 de Nov. de 2021
Editada: Walter Roberson el 8 de Jul. de 2025
tt = floor(linspace(1,length(A),100));
red_A = A(tt) ;

2 comentarios

Telema Harry
Telema Harry el 10 de Nov. de 2021
Thank you
Ünal Dikmen
Ünal Dikmen el 8 de Jul. de 2025
this code also an elegant way :)

Iniciar sesión para comentar.

Más respuestas (1)

KSSV
KSSV el 10 de Nov. de 2021
a = 1;
b = 200;
A = (b-a).*rand(1000,1) + a;
x1 = 1:length(A) ;
x2 = linspace(1,length(A),100) ;
Anew = interp1(x1,A,x2) ;

Categorías

Productos

Versión

R2021a

Etiquetas

Preguntada:

el 10 de Nov. de 2021

Editada:

el 8 de Jul. de 2025

Community Treasure Hunt

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

Start Hunting!

Translated by