Inserting data of one matrix into another
Show older comments
If I have a vector a
0
0
1
1
0
0
and a vector b
5
6
and I want to input the data of b into the nonzero elements of a (which will always be together and matching the dimensions of b), so that vector c reads
0
0
5
6
0
0
What is an easy way to do this? Thank you!
Another example that it needs to work for:
a b c
_ _ _
0 4 0
0 8 0
1 3 ----> 4
1 7 8
1 3
1 7
Accepted Answer
More Answers (2)
>> a = [false;false;true;true;false;false];
>> b = [5;6];
>> c = zeros(size(a));
>> c(a) = b
c =
0
0
5
6
0
0
And the same for the second example:
>> a = [false;false;true;true;true;true];
>> b = [4;8;3;7];
>> c = zeros(size(a));
>> c(a) = b
c =
0
0
4
8
3
7
3 Comments
Shane Hagen
on 3 Apr 2015
any insight on my issue stephen? I would really appreciate any help.
Shane Hagen
on 3 Apr 2015
I posted the question :Inserting data into matrix of zeros from another matrix.
try simple
a=[0;0;1;1;0;0];
b=[5;6];
p=find(a>0);
a(p)=b
a =
0
0
5
6
0
05 Comments
James Tursa
on 3 Apr 2015
You have totally missed the issue. The 1's & 0's vector "a" is logical. So your scheme doesn't work. E.g.,
>> a = logical([0 0 1 1 0 0]);
>> b = [5 6];
>> p = find(a>0);
>> a(p) = b
a =
0 0 1 1 0 0
LUI PAUL
on 3 Apr 2015
its not mentioned 'logical'.Chris said only vector....logical may not be used....
James Tursa
on 3 Apr 2015
Go to Adam's answer. Read the 5th and 6th comments by Chris and Adam. They clearly show that the fundamental issue is that "a" is logical, and Adam posts a solution for this that works when "a" is logical.
for logical a,...try this
a = logical([0 0 1 1 0 0]);
a=double(a);
b = [5 6];
p = find(a>0);
a(p) = b
a =
0 0 5 6 0 0
what do you think @James will it work?
James Tursa
on 3 Apr 2015
Yes.
Categories
Find more on MATLAB 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!