Adding zeros at the end of arrays in a loop

2 次查看(过去 30 天)
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 个评论
hazal akova
hazal akova 2020-12-9
I have generated them by using shortestpath between specified nodes in Matlab workspace. For instance; path2 = [ 1732 425 417 1747 ].
Stephen23
Stephen23 2020-12-9
"I have generated them by using shortestpath between specified nodes in Matlab workspace"
Did you write out all 184 variables by hand?

请先登录,再进行评论。

回答(1 个)

Ameer Hamza
Ameer Hamza 2020-12-9
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)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by