hi every one, i need to ask a question, thank you
Show older comments
if i have a row vector like this A=[ 0 1 1 1 0 0 1 1 0 1 ]
and another vector B=[ 1 2 3 4 5 6 ]
and i need to put the element of B in order in A when the element is equal to 1
so if it can possibile i need to return a vector with the dimensions of B like this [ 0 1 2 3 0 0 4 5 0 6 ] , how can i do it if it's possibile to do it in matlab
thank you
Accepted Answer
More Answers (3)
result=sparse(1,find(A),B)
Catalytic
on 30 Jun 2019
A=double(A);
A(logical(A))=B;
[i,j]=find(A(:));
result=accumarray([i,j],B(:),size(A.')).'
4 Comments
Image Analyst
on 30 Jun 2019
I'm not understanding why this was accepted or even how it works.
My code below
A=[ 0 1 1 1 0 0 1 1 0 1 ];
B=[ 1 2 3 4 5 6 ];
out = A; % Initialize
out(logical(A)) = B % Assign B to "1" locations in A
gives
out =
0 1 2 3 0 0 4 5 0 6
However Matt's code
A=[ 0 1 1 1 0 0 1 1 0 1 ];
B=[ 1 2 3 4 5 6 ];
result=accumarray(find(A),B(:),size(A))
gives
Error using accumarray
Second input VAL must be a vector with one element for each row in SUBS, or a scalar.
Error in test3 (line 3)
result=accumarray(find(A),B(:),size(A))
What am I not getting?
Image Analyst
on 1 Jul 2019
I think it's because the poster did not see what she wanted to see. So instead of seeing:
0 1 2 3 0 0 4 5 0 6
like she asked for, you see
result =
(1,2) 1
(1,3) 2
(1,4) 3
(1,7) 4
(1,8) 5
(1,10) 6
mina massoud
on 1 Jul 2019
Categories
Find more on Matrices and Arrays 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!