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
dpb 2018 年 5 月 2 日

0 投票

Don't use sequentially number variables; use arrays or alternate storage techniques instead.
See the FAQ for why not and more better ways: <Variables A1 A2....A10>

3 件のコメント

KK JJ
KK JJ 2018 年 5 月 2 日
in implementation, my variables will not be sequentially numbered. they will bear meanings. i.e.
apple1 = nonzeros(reshape(apple,[1,10]));
nvidia1 = nonzeros(reshape(nvidia,[1,10]));
....
qualcomm1 = nonzeros(reshape(qualcomm,[1,10]));
again, is there a way to simply this repeated use of the same function?
dpb
dpb 2018 年 5 月 3 日
編集済み: dpb 2018 年 5 月 3 日
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
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.

サインインしてコメントする。

Jan
Jan 2018 年 5 月 3 日
編集済み: dpb 2018 年 5 月 3 日

0 投票

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 ExchangeMatrix Indexing についてさらに検索

質問済み:

2018 年 5 月 2 日

コメント済み:

2018 年 5 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by