Adding zeros at the end of arrays in a loop

5 Ansichten (letzte 30 Tage)
hazal akova
hazal akova am 9 Dez. 2020
Kommentiert: Stephen23 am 9 Dez. 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.
Thanks in advance.
  4 Kommentare
hazal akova
hazal akova am 9 Dez. 2020
I have generated them by using shortestpath between specified nodes in Matlab workspace. For instance; path2 = [ 1732 425 417 1747 ].
Stephen23
Stephen23 am 9 Dez. 2020
"I have generated them by using shortestpath between specified nodes in Matlab workspace"
Did you write out all 184 variables by hand?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ameer Hamza
Ameer Hamza am 9 Dez. 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)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by