Adding zeros at the end of arrays in a loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I have 184 arrays with different lengths named as 'path1', 'path2', 'path3' ...'path184'. The longest of these is 1*35 long and is named as 'path34'.
I want to add zeros to the end of these arrays to make them equal to the longest one.
path1(numel(path34))=0;
This is the line for making the first one.
I want to write it as a loop, but do not know where to begin.
Thanks in advance.
4 comentarios
Stephen23
el 9 de Dic. de 2020
"I have generated them by using shortestpath between specified nodes in Matlab workspace"
Did you write out all 184 variables by hand?
Respuestas (1)
Ameer Hamza
el 9 de Dic. de 2020
Finally, you have encountered the problem of naming variables like var1, var2, var3, ... This thread has a detailed discussion on this topic and explains why they are a bad coding practice: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval.
The correct way to handle such cases is to use arrays. Although eval() is usually unrecommended, however, you can use this once to convert all of your variables to a cell array
paths = eval(['{' sprintf('path%d,', 1:184) '}'])
and then there are several ways to make all vectors of equal length
n = max(cellfun(@numel, paths))
paths_equal = cellfun(@(x) [x zeros(1,n-numel(x))], paths, 'uni', 0)
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!