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!