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!