What is a simple way to check if a collection of vectors all have the same number of elements
22 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jon
el 22 de Sept. de 2023
Comentada: Jon
el 2 de Oct. de 2023
I am look for a nice simple way to check if a collection of vectors all have the same number of elements. For example this might be used to validate some inputs to a function, or otherwise check compatibility before performing other operations.
Here's my current approach, which works, but I wonder if someone has simpler way of doing the same thing
a = rand(3,1);
b = rand(3,1);
c = rand(4,1);
d = rand(3,1);
vecs = {a,b,c,d};
n = cellfun(@numel,vecs);
if any(n(1)~=n)
error('all vectors must be same length')
end
2 comentarios
Torsten
el 22 de Sept. de 2023
Why not renaming a,b,c and d to vecs{1},vecs{2},vecs{3} and vecs{4} ? Should make things easier ...
Bruno Luong
el 22 de Sept. de 2023
Editada: Bruno Luong
el 22 de Sept. de 2023
I'm half serious but:
The simplest way? IMO just don't do any check, just rely on MATLAB, if any operation on vecs with incompatible sizes will imply error, just let MATLAB throw an error instead of
error('all vectors must be same length')
Respuesta aceptada
Bruno Luong
el 22 de Sept. de 2023
Editada: Bruno Luong
el 22 de Sept. de 2023
if any(n(1)~=n)
The above will crash if your cell is empty.
IMO
if any(diff(n))
is a more robust test. Thus you can do the test in a single statement
if any(diff(cellfun(@numel,vecs)))
% ...
end
And last but not least, if performance matters, use this
if any(diff(cellfun('prodofsize',vecs)))
% ...
end
instead of @numel.
Here is why
vecs = arrayfun(@(x) zeros(randi(10),1), 1:1e6, 'unif', 0);
timeit(@()cellfun(@numel, vecs),1)
timeit(@()cellfun('prodofsize', vecs),1)
Más respuestas (1)
Walter Roberson
el 22 de Sept. de 2023
a = rand(3,1);
b = rand(3,1);
c = rand(4,1);
d = rand(3,1);
vecs = {a,b,c,d};
n = cellfun(@numel,vecs,'uniform',0);
if ~isequal(n{:})
error('all vectors must be same length')
end
6 comentarios
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!