Reshaping a matrix based on the first row
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Voss
il 24 Apr 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 Commenti
Voss
il 27 Apr 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
il 27 Apr 2024
Modificato: Stephen23
il 27 Apr 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 Commento
Stephen23
il 27 Apr 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)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!