# Adding zeros at the end of arrays in a loop

5 views (last 30 days)
hazal akova on 9 Dec 2020
Commented: Stephen23 on 9 Dec 2020
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.
Stephen23 on 9 Dec 2020
"I have generated them by using shortestpath between specified nodes in Matlab workspace"
Did you write out all 184 variables by hand?

Ameer Hamza on 9 Dec 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)