1) I want to replace the first nonzero element of each row of a matrix
with -1
Example
5 0 10
0 3 7
0 6 0
Becomes..
-1 0 10
0 -1 7
0 -1 0
2) Is there any way to do a multiplication like the one below.. where
all of the elements of row 1 in Matrix B are multiplied by element 1
of vector A.... all row 2 elements in B are multiplied by element 2 in
A, etc...
Example...
A x B = C
1 1 2 1 2
2 1 2 2 4
3 1 2 3 6
Thank you!
K>> A=[5 0 10;
0 3 7;
0 6 0];
A(find(A~=0,size(A,1)))=-1
A =
-1 0 10
0 -1 7
0 -1 0
> 2) Is there any way to do a multiplication like the one below.. where
> all of the elements of row 1 in Matrix B are multiplied by element 1
> of vector A.... all row 2 elements in B are multiplied by element 2 in
> A, etc...
>
> Example...
>
> A x B = C
> 1 1 2 1 2
> 2 1 2 2 4
> 3 1 2 3 6
>
>
>
> Thank you!
K>> A
A =
1
2
3
K>> B
B =
1 2
1 2
1 2
K>> cell2mat(arrayfun(@(i) A(:).*B(:,i),[1:2],'UniformOutput',false))
ans =
1 2
2 4
3 6
K>>
--Nasser
Wow... THanks so much! Small problem - the method of replacing the
first nonzero elements with -1 worked, but not quite 100% of the
time. (the other code worked perfectly though)
For instance, in the matrix below..
50 75 0
50 0 100
0 75 100
75 100 0
0 75 100
The formula resulted in
-1 75 0
-1 0 100
0 -1 100
-1 100 0
0 75 100
For some reason, the 75 in the last row was not converted..
I'm not sure why
Doug
A =
1
2
3
B =
1 2
1 2
1 2
bsxfun(@times,A,B)
" Small problem - the method of replacing the
first nonzero elements with -1 worked, but not quite 100% of the
time. (the other code worked perfectly though)
For instance, in the matrix below..
50 75 0
50 0 100
0 75 100
75 100 0
0 75 100
The formula resulted in
-1 75 0
-1 0 100
0 -1 100
-1 100 0
0 75 100
For some reason, the 75 in the last row was not converted..
I'm not sure why
Doug"
There is a bug :)
I'll fix it soon. I am making coffee now, please wait a minute
--Nasser
Ok, coffee is done :), here it is
EDU>> clear all
A=[50 75 0;
50 0 100;
0 75 100;
75 100 0;
0 75 100;
0 75 100];
[I,J]=ind2sub(size(A),find(A~=0));
[b,c]=unique(I,'first');
A(sub2ind(size(A),b,J(c)))=-1
A =
-1 75 0
-1 0 100
0 -1 100
-1 100 0
0 -1 100
0 -1 100
EDU>>
BINGO! That did it. No idea how it did it. But it did it. Thank
you sir. What do I owe you?
THanks also Jean-Claude... I tried yours but couldn't get it to work
(which is almost certainly my / the operator's fault).
B=cumsum(A~=0,2)>0
B=[false(size(B,1),1) B]
A(logical(diff(B,1,2))) = -1
% Bruno
That works too - thanks!
What about the one-liner:
A((cumsum(~~A,2)==1) & (A ~= 0)) = -1
Jos
Nice.
When working with matrices and vectors, Matlab really is very powerfull.
--Nasser
> What about the one-liner:
>
Nice !
Bruno