how to convert 2d to id

2 views (last 30 days)
studentambitious
studentambitious on 6 Jul 2016
Edited: Azzi Abdelmalek on 6 Jul 2016
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 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 6 Jul 2016
You omitted to show us the expected result
Stephen23
Stephen23 on 6 Jul 2016
@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.

Sign in to comment.

Answers (3)

KSSV
KSSV on 6 Jul 2016
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 on 6 Jul 2016
Edited: Azzi Abdelmalek on 6 Jul 2016
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 on 6 Jul 2016
Edited: José-Luis on 6 Jul 2016
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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!