how to convert 2d to id

조회 수: 3 (최근 30일)
studentambitious
studentambitious 2016년 7월 6일
편집: Azzi Abdelmalek 2016년 7월 6일
i want to convert a 5x3 matrix say A into 1d but before reshaping it i need to omit certain values from every row of A.number of values i need to omit is given in another matrix say C. for eg
A=[5 4 3 8 9 6; 2 1 3 2 5 ;4 3 5 7 6]
C=[1; 3; 4]
what i need is to convert matrix A into an array such that from first row of A last one value is to be emitted from second row last 3 values are to be removed and similarly from third row last 4 values need to be omitted. number of values to be omitted is given in row matrix C
please help
  댓글 수: 2
Azzi Abdelmalek
Azzi Abdelmalek 2016년 7월 6일
You omitted to show us the expected result
Stephen23
Stephen23 2016년 7월 6일
@studentambitious: your matrix A generates this error:
>> A=[5 4 3 8 9 6; 2 1 3 2 5 ;4 3 5 7 6]
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

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

답변 (3개)

KSSV
KSSV 2016년 7월 6일
A=[5 4 3 8 9 ; 2 1 3 2 5 ;4 3 5 7 6] ;
B = [1 3 4] ;
iwant = fliplr(A) ;
for i = 1:length(B)
id = B(i) ;
iwant(i,1:id) = NaN ;
end
iwant = fliplr(iwant) ;
idx = ~isnan(iwant) ;
iwant = iwant(idx) ;

Azzi Abdelmalek
Azzi Abdelmalek 2016년 7월 6일
편집: Azzi Abdelmalek 2016년 7월 6일
A=[5 4 3 8 9 ; 2 1 3 2 5 ;4 3 5 7 6]
C=[1; 3; 4]
n=size(A,2);
m=numel(C);
out=A(:);
idx=arrayfun(@(x) sub2ind(size(A),x*ones(1,C(x)),n:-1:n-C(x)+1),(1:m),'un',0)
idx=cell2mat(idx)
out(idx)=[]
%Or
A=[5 4 3 8 9 ; 2 1 3 2 5 ;4 3 5 7 6];
C=[1; 3; 4];
[n,m]=size(A);
B=zeros(1,n*m-sum(C));
idx=1;
for k=1:n
kk=1:m-C(k);
p=numel(kk);
B(1,idx:idx+p-1)=A(k,kk);
idx=idx+p;
end
B

José-Luis
José-Luis 2016년 7월 6일
편집: José-Luis 2016년 7월 6일
Probably faster:
A=[5 4 3 8 9 ; 2 1 3 2 5 ;4 3 5 7 6];
C=[1; 3; 4];
numCol = size(A,2);
A(bsxfun(@gt,numCol - C,1:numCol)) = NaN
Please note that you did not specify how you wanted your results stored. Here, I replace the unnecessary data with NaN.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by