Insert missing values in specified positions and use for loop

Hi everybody could anyone help me in my problem: i have an array with known missed values in known places . I want to insert these values in the specified positions and do it for many arrays. Example a=[2 4 6 3 3 5 3 4 1 0 0 0 0] Li=[2 8 10 12] %locations of values in array Val=[6 7 8 9] Solution should be Sol=[2 6 4 6 3 3 5 7 3 8 4 9 1] Also how to apply this in for loop for multiple arrays Thanks in advance

 채택된 답변

KSSV
KSSV 2020년 6월 25일

0 개 추천

This problem is dicussed multiple times....you can checki there in this useful link:

댓글 수: 5

Thanks KSSV but the link you provide is assigning one value in one location but here I found a difficult in assigning multiple values and in multiple arrays For example a_matrix=[1 2 3 4 5 6 7 8 9; 3 4 1 2 5 6 7 2 8; 9 8 1 2 5 6 7 2 3]; I want to insert [ 6 7 8 9] in column [2 8 10 12] So the new matrix will be a_newmatrix= [1 6 2 3 4 5 6 7 7 8 8 9 9; 3 6 4 1 2 5 6 7 7 8 2 9 8; 9 6 8 1 2 5 6 7 7 8 2 9 3] If you could and don't mind helping me.
a=[2 4 6 3 3 5 3 4 1 0 0 0 0] ;
Li=[2 8 10 12] %locations of values in array
Val=[6 7 8 9] ;
Sol=[2 6 4 6 3 3 5 7 3 8 4 9 1] ;
iwant = zeros(size(a)) ; % initlialize the required array
iwant(Li) = Val ;
% Mkae logical indices
idx = logical(zeros(size(a))) ;
idx(Li) = 1 ;
iwant(~idx) = a(a~=0) ;
Thanks KSSV for your time and reply. It works very good for the array but I still found problem for the matrix. I write this for loop to solve it for i=1:3 %3 is no of rows in matrix for j=1:4 % 4 is length of li iwant(I,li(j))=val(j); Idx(i)=logical(zeros(sizeallol(i))); idx(i,li(j))=1 %%%the problem in the following line %%% iwant(~idx)=a(a~=0) %how to make it inside loop end end Thanks in advance and sorry for little knowledge in matlab
a = [1 2 3 4 5 6 7 8 9; 3 4 1 2 5 6 7 2 8; 9 8 1 2 5 6 7 2 3];
val = [ 6 7 8 9] ;
col = [2 8 10 12] ;
b = [1 6 2 3 4 5 6 7 7 8 8 9 9; 3 6 4 1 2 5 6 7 7 8 2 9 8; 9 6 8 1 2 5 6 7 7 8 2 9 3] ;
[m,n] = size(a) ; p = length(col) ;
iwant = zeros(m,n+p) ;
for i = 1:m
iwant(i,col) = val ;
% Make logical indices
idx = logical(zeros(1,n+p)) ;
idx(col) = 1 ;
iwant(i,~idx) = a(i,:) ;
end
Thank you very much for your help

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2020년 6월 25일

댓글:

2020년 6월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by