Reshaping a matrix based on the first row
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Voss
2024-4-24
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 个评论
Voss
2024-4-27
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
2024-4-27
编辑:Stephen23
2024-4-27
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 个评论
Stephen23
2024-4-27
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!