how to simplify/consolidate repeat functions
古いコメントを表示
Hi,
I need to apply the same function to multiple variables in exactly the same way, i.e.
a1 = nonzeros(reshape(a,[1,10]));
b1 = nonzeros(reshape(b,[1,10]));
....
z1 = nonzeros(reshape(z,[1,10]));
given the repeating nature, is there a way to consolidate these commands?
thanks,
Kevin
回答 (2 件)
dpb
2018 年 5 月 2 日
0 投票
Don't use sequentially number variables; use arrays or alternate storage techniques instead.
3 件のコメント
KK JJ
2018 年 5 月 2 日
Well, they are numbered sequentially (albeit with an implict '0'), you're turning each into a new variable; why not just retain apple? Also as written, the code will fail unless there are precisely 10 non-zero elements in the variable to begin with.
As the FAQ describes, the way to "have your cake and eat it too" with names and addressing is structure with dynamic field names. At the time the FAQ was written, that was basically the only option; now there's also the table which also allows for named variables that can be dynamically referenced.
Guillaume
2018 年 5 月 4 日
in implementation, my variables will not be sequentially numbered
It may not be a numbered sequence, but it's still a sequence. If you're using any kind of sequence to name your variables, it's wrong. All the variables clearly belong together in some container.
If you have a set of variables, store them in a cell array instead of of different variables. Then the processing in a loop is easy:
nonZeroC = zeros(1, numel(C));
for k = 1:numel(C)
nonZeroC(k) = nonzero(reshape(C{k}, 1, 10));
end
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!