matlab - how to vectorize array reformatting? -
i have .csv file data on each line in format (x,y,z,t,f)
, f
value of function @ location (x,y,z)
@ time t
. each new line in .csv gives new set of coordinates (x,y,z,t)
, accompanying value f
. .csv not sorted.
i want use imagesc
create video of data in xy
-plane, time progresses. way i've done reformatting m more usable imagesc
. i'm doing 3 nested loops, this
m = csvread('file.csv'); uniquex = unique(m(:,1)); uniquey = unique(m(:,2)); uniquet = unique(m(:,4)); m_reformatted = zeros(length(uniquex), length(uniquey), length(uniquet)); = 1:length(uniquex) j = 1:length(uniquey) k = 1:length(uniquet) m_reformatted(i,j,k) = m( ... m(:,1)==uniquex(i) & ... m(:,2)==uniquey(j) & ... m(:,4)==uniquet(k), ... 5 ... ); end end end
once have m_reformatted
, can loop through timesteps k
, use imagesc
on m_reformatted(:,:,k)
. doing above nested loops slow. possible vectorize above? if so, outline of approach helpful.
edit: noted in answers/comments below, made mistake in there several possible z-values, haven't taken account. if single z-value, above ok.
this vectorized solution allows negative values of x
, y
, many times faster non-vectorized solution (close 20x times test case @ bottom).
the idea sort x
, y
, , t
values in lexicographical order using sortrows
, using reshape
build time slices of m_reformatted
.
the code:
idx = find(m(:,3)==0); %// find rows z==0 m2 = m(idx,:); %// m2 has rows z==0 m2(:,3) = []; %// delete z coordinate in m2 m2(:,[1 2 3]) = m2(:,[3 1 2]); %// change (x,y,t,f) (t,x,y,f) m2 = sortrows(m2); %// sort rows t, x, y numt = numel(unique(m2(:,1))); %// number of unique t values numx = numel(unique(m2(:,2))); %// number of unique x values numy = numel(unique(m2(:,3))); %// number of unique y values %// fill time slice matrix data m_reformatted = reshape(m2(:,4), numy, numx, numt);
note: assuming y
refers columns of image , x
refers rows. if want these flipped, use m_reformatted = permute(m_reformatted,[2 1 3])
@ end of code.
the test case used m
(to compare result other solutions) has nxnxn
space t
times slices:
n = 10; t = 10; [x,y,z] = meshgrid(-n:n,-n:n,-n:n); numpoints = numel(x); x=x(:); y=y(:); z=z(:); s = repmat([x,y,z],t,1); t = repmat(1:t,numpoints,1); m = [s, t(:), rand(numpoints*t,1)]; m = m( randperm(size(m,1)), : );
Comments
Post a Comment