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
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 Exchange에서 Matrix 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