필터 지우기
필터 지우기

How to efficiently replace value at the n last column?

조회 수: 1 (최근 30일)
balandong
balandong 2018년 9월 4일
댓글: balandong 2018년 9월 4일
Dear all, The objective was to replace the value at the end of a column. I have make a simple case but wonder if there is another way to make it more compact and efficient?
Thanks in advance
f_sbj=2
sA=23;
A =1:sA;
appndOut=cell(sA,1);
for f_x=1:sA
Out = nchoosek(A, f_x);
[rows, columns] = find(Out==f_sbj);
Out(rows, :) = [];
[m,n] = size(Out );
newNan=nan(m,(sA-n));
appndOut{f_x}=[newNan Out];
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2018년 9월 4일
That code appears to insert at the beginning of columns, not replace at the end of columns.
The code can be made more compact, but not necessarily more efficient.
balandong
balandong 2018년 9월 4일
Thanks for the quick response, Appreciate if you can some idea to make it more compact

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2018년 9월 4일
lastNcol = @(M, N) M(:,end-N+1:end);
NanPrePad = @(M, N) lastNcol( [nan(size(M,1), N), M], N);
select_and_prepad = @(M, N) NanPrePad( M(all(M~=f_sbj, 2),:) );
appndOut = arrayfun(@(f_x) select_and_prepad(nchoosek(A, f_x), sA), (1:sA).', 'uniform', 0);
You can use shorter names for the anonymous functions if you find the above to not be compact enough.
Though I wonder why you do not do something like
A = setdiff(1:sA, f_sbj);
That would eliminate the possibility of f_sbj being generated by the nchoosek, so it would not be necessary to delete any rows containing f_sbj.
  댓글 수: 3
Walter Roberson
Walter Roberson 2018년 9월 4일
f_sbj=2
sA=23;
A =1:sA;
lastNcol = @(M, N) M(:,end-N+1:end);
NanPrePad = @(M, N) lastNcol( [nan(size(M,1), N), M], N);
select_and_prepad = @(M, N) NanPrePad( M(all(M~=f_sbj, 2),:), N );
appndOut = arrayfun(@(f_x) select_and_prepad(nchoosek(A, f_x), sA), (1:sA).', 'uniform', 0);
This takes a moment to execute.
balandong
balandong 2018년 9월 4일
Works like a charm, Thanks Walter

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by