matrix creation from a loop
1 次查看(过去 30 天)
显示 更早的评论
Hello all,
I would like to create 60 vector columns of zeros (6964,1) called lat_01_days, lat_02days, lat_03_days until 60. I know I could write them one by one but if i know How to create a loop to create them it would be better also for future research. Can someone help mep lease?
regards
Jonathan
2 个评论
Stephen23
2020-9-17
"I would like to create 60 vector columns of zeros (6964,1) called lat_01_days, lat_02days, lat_03_days until 60."
Numbering variables like that is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) intoe variable names is a sign that you are doing something wrong.
"I know I could write them one by one ..."
Ouch!
"...but if i know How to create a loop to create them it would be better also for future research"
In fact what "would be better also for future research" is to avoid numbered variables entirely:
回答(3 个)
Walter Roberson
2020-9-17
if i know How to create a loop to create them it would be better also for future research.
Our long experience is that it would make your future research worse instead of better.
Stephen23
2020-9-17
The simplest and most efficient solution is to just create one matrix:
lat = zeros(6964,60)
which you can then trivially access using indexing. There is no point in making it more complex than that.
0 个评论
Ruger28
2020-9-17
编辑:Ruger28
2020-9-17
The two other answers are a more correct way of doing it. There is no need to create this many variables in your workspace. However, if you must...
You should use a structure instead of individual variables.
Blank_Vec = zeros(6964,1);
Num_Cols = 60;
for ii = 1:Num_Cols
name = sprintf('lat_%i_days',ii);
ZeroColStruct.(name) = Blank_Vec;
end
if you absolutely MUST have individual variables, one method is this:
% Removed due to being a terrible way to do something
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!