Filter löschen
Filter löschen

How to efficiently replace value at the n last column?

1 Ansicht (letzte 30 Tage)
balandong
balandong am 4 Sep. 2018
Kommentiert: balandong am 4 Sep. 2018
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 Kommentare
Walter Roberson
Walter Roberson am 4 Sep. 2018
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 am 4 Sep. 2018
Thanks for the quick response, Appreciate if you can some idea to make it more compact

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 4 Sep. 2018
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 Kommentare
Walter Roberson
Walter Roberson am 4 Sep. 2018
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 am 4 Sep. 2018
Works like a charm, Thanks Walter

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by