How do I transform a 3d vector into a 1d vector?
How to convert 3D image to 1D data?
How to divide a 3D array into one dimensional cell array
How to convert 3D matrix to 1D?
I have a 1x1xn double that I'd like to change to nx1 for plotting purposes. Is there a way to do this that doesn't take a lot of runtime?
EDIT: Apparently using squeeze() does the job.
Here's what I'd do:
[B i]=max(reshape(A,[],size(A,3)));
[II,JJ]=ind2sub(size(A),i );
The only limitation is that it wont treat well cases where there is more than one max per 2D slice.
You could convert it to a cell array and use cellfun
B=mat2cell(reshape(A,[1, size(A,2).^2, size(A,3)]),[1],[size(A,2).^2], [ones(size(A,3),1)]);
[M,I]= cellfun(@max,B)
[R,C] = ind2sub(size(A),I);
M contains the maximum value and I the corresponding index.
Assuming that A is a 3x3x2 array.
A =[
0.7952 0.4456 0.7547
0.1869 0.6463 0.2760
0.4898 0.7094 0.6797];
A(:,:,2) =[
0.6551 0.4984 0.5853
0.1626 0.9597 0.2238
0.1190 0.3404 0.7513];
Convert each slice into a 1x9x2 cell array
B=mat2cell(reshape(A,[1, size(A,2).^2, size(A,3)]),[1],[size(A,2).^2], [ones(size(A,3),1)]);
B(:,:,1) =
[1x9 double]
B(:,:,2) =
[1x9 double]
Take the maximum of each slice. R is the row and C is the column for the respective maximum value in M.
[M,I]= cellfun(@max,B)
[R,C] = ind2sub(size(A),I)
R(:,:,1) =
1
R(:,:,2) =
2
C(:,:,1) =
1
C(:,:,2) =
2
Please do not use arrayfun as it is essentially a loop. Use the mighty bsxfun instead combined with permute:
Esun = 1:8; % Esun = [1 2 3 4 5 6 7 8];
B = bsxfun(@rdivide, A, permute(Esun, [1 3 2]));
The variable A is the 3D matrix that you have that is of size 256 x 3527 x 8. The call to permute uses Esun and converts it into a 3D vector of 1 row and 1 column. After, bsxfun broadcasts the 3D vector so that it becomes a 3D matrix of size 256 x 3527 x 8 where each slice i represents the ith value in Esun. We then perform the element-wise division.
This basically performs the repetitive array operation that you're speaking of, but the replication is done internally in bsxfun and is faster than if you were to create the repetitive array first then perform the division.
You can use arrayfun as following:
c=arrayfun(@(i) X(:,:,i)*Esun(i),1:8,'UniformOutput',0);
Assuming that X is your image array. In the above, MATLAB return a 1x8 cell array, then you can use cat function to obtain the new array:
B = cat(3, c{:}); % cat all cell elements in 3-rd dim