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!