Reshaping a matrix based on the first row
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I am trying to make a for loop that creates a new array that groups row data into corresponding columns:
My current arrays are something like this (both same size):
[270 270 270 271 272 272 273 273 273]
[12 2 3 14 5 2 6 8 11]
I want 4 columns (each representing 270, 271, 272, 273 respectively) that will produce something like this:
[12 14 5 6; 2 NAN 2 8; 3 NAN NAN 11]
my for loop is currently creating a 9 by 3 array that has the correct values in each column but is producing a bigger shape (more NANs).
for i = 1:length(data1)
for j = 1:length(number)
if data1(i) == number(j) % my dataset == a number array [270, 271, 272, 273]
newArray(i,j) = data2(i);
end
end
end
0 comentarios
Respuestas (2)
Voss
el 24 de Abr. de 2024
Here's one way:
A = [270 270 270 271 272 272 273 273 273];
B = [ 12 2 3 14 5 2 6 8 11];
[~,~,cidx] = unique(A,'stable');
ridx = accumarray(cidx,A,[],@(x){1:numel(x)});
ridx = [ridx{:}].';
NR = max(ridx);
NC = max(cidx);
result = NaN(NR,NC);
result(sub2ind([NR,NC],ridx,cidx)) = B
4 comentarios
Voss
el 27 de Abr. de 2024
A = load('EventDays.mat').doy_e
B = load('Events.mat').events
idx = ~isnan(A);
[~,~,cidx] = unique(A(idx),'stable');
ridx = accumarray(cidx,A(idx),[],@(x){1:numel(x)});
ridx = [ridx{:}].';
NR = max(ridx);
NC = max(cidx);
result = NaN(NR,NC);
result(sub2ind([NR,NC],ridx,cidx)) = B(idx)
Stephen23
el 27 de Abr. de 2024
Editada: Stephen23
el 27 de Abr. de 2024
A = [270,270,270,271,272,272,273,273,273];
B = [ 12, 2, 3, 14, 5, 2, 6, 8, 11];
X = ~isnan(A);
C = findgroups(A(X));
R = grouptransform(ones(nnz(X),1),C(:),@cumsum);
M = accumarray([R,C(:)],B(X),[],[],NaN)
1 comentario
Stephen23
el 27 de Abr. de 2024
Using your uploaded data (my code is unchanged). Note that your data also has NaNs in it, which so far you have not explained how you want to handle. I will remove them.
A = load('EventDays.mat').doy_e
B = load('Events.mat').events
X = ~isnan(A);
C = findgroups(A(X));
R = grouptransform(ones(nnz(X),1),C(:),@cumsum);
M = accumarray([R,C(:)],B(X),[],[],NaN)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!