Adding zeros at the end of arrays in a loop

5 views (last 30 days)
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.
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.
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?

Sign in to comment.

Answers (1)

Ameer Hamza
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:
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)

Community Treasure Hunt

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

Start Hunting!