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

Answers (2)

dpb
dpb on 2 May 2018
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 Comments

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 on 3 May 2018
Edited: dpb on 3 May 2018
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.
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.

Sign in to comment.

Jan
Jan on 3 May 2018
Edited: dpb on 3 May 2018
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

Asked:

on 2 May 2018

Commented:

on 4 May 2018

Community Treasure Hunt

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

Start Hunting!