Supposed I have matrix :
mat= [1 2 3;
2 3 4;
3 4 5;]
test = [2 3 4 5 6 7;
3 4 5 6 7 8;
7 8 9 4 5 6 ]
All I want to do is do these operations:
mat1=[(1-2) (2-3) (3-4);
(2-3) (3-4) (4-5);
(3-7) (4-8) (5-9)]
and
mat2=[(1-5) (2-6) (3-7);
(2-6) (3-7) (4-8);
(3-4) (4-5) (5-6)]
and save the min value between mat1
and mat2
then save the index of the value from. I want my answers like these :
ans = [-4 -4 -4;
-4 -4 -4;
-4 -4 -4]
index = [2 2 2;
2 2 2;
1 1 1]
I dont need to save mat1
and mat2
, I just need ans
and index
(to make the computation faster). Is there any help how to code it? Thank you.
You may use bsxfun
like this for a generalized case.
Code
%%// Slightly bigger example than the original one
mat= [
1 2 3 6;
2 3 4 2;
3 4 5 3;]
test = [
2 3 4 8 5 6 7 1;
3 4 5 3 6 7 8 7;
7 8 9 6 4 5 6 3]
[M,N] = size(mat);
[M1,N1] = size(test);
if N1~=2*N %%// Check if the sizes allow for the required op to be performed
error('Operation could not be performed');
end
[min_vals,index] = min(bsxfun(@minus,mat,reshape(test,M,N,2)),[],3)
Output
min_vals =
-4 -4 -4 -2
-4 -4 -4 -5
-4 -4 -4 -3
index =
2 2 2 1
2 2 2 2
1 1 1 1
mat1 = mat-test(:,1:3)
mat2 = mat-test(:,4:end)
theMin = bsxfun(@min,mat1,mat2)
-4 -4 -4
-4 -4 -4
-4 -4 -4
To build the index
idx = mat2-mat1;
I2 = find(idx<=0);
I1 = find(idx>0);
idx(I2) = 2;
idx(I1) = 1;
2 2 2
2 2 2
1 1 1
I think these four lines will do it
matDifs = bsxfun(@minus, mat, reshape(test, 3, 3, 2)); % construct the two difference matrices
values = min(matDifs, [], 3); % minimum value along third dimension
indices = ones(size(values)); % create matrix of indices: start out with ones
indices(matDifs(:,:,2)<matDifs(:,:,1)) = 2; % set some indices to 2
This does almost the same thing as @Divakar's solution. It is less compact but slightly more readable, I think.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.