Cell entries as the third dimension of the cell2mat matrix.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Anish Pradhan
am 20 Dez. 2022
Kommentiert: Anish Pradhan
am 20 Dez. 2022
I am using this code to initialize A and B:
for k=1:N
for j=1:N
A{k,j}=S(:,j).*D(k,:).';
B(k,j,:)=A{k,j};
end
end
Essentially, I want to create B directly from A without explicit loops as I found a vectorized way to create A.
2 Kommentare
Rik
am 20 Dez. 2022
You can probably use reshape and repmat to get implicit expansion to do this for you. What have you tried?
Also, you don't need A at all here to get B. Do you need A later?
Akzeptierte Antwort
Adam Danz
am 20 Dez. 2022
Compute B outside of the loop
for k=1:N
for j=1:N
A{k,j}=S(:,j).*D(k,:).';
end
end
B = permute(reshape(horzcat(A{:}),size(A,1),size(A,2),[]),[2 3 1]);
Confirm that it's equal to the loop version of B
N = 3; % Demo data
S = 100 * rand(N);
D = 5 * rand(N);
for k=1:N
for j=1:N
A{k,j}=S(:,j).*D(k,:).';
BLoop(k,j,:)=A{k,j};
end
end
B = permute(reshape(horzcat(A{:}),size(A,1),size(A,2),[]),[2 3 1]);
isequal(BLoop, B) % True means BLoop and B are equal
Explanation
This is our goal
BLoop
First the columns of A are concatenated into a matrix
horzcat(A{:})
Then the matrix is reshaped into a 3D array according to the shape of A. The shape looks like our goal but note that the order of the values do not match the goal.
reshape(horzcat(A{:}),size(A,1),size(A,2),[])
Finally, the dimensions of the 3D array are rearranged to move dim 1 to dim 3 per the instructions in "BLoop(k,j,:)"
B = permute(reshape(horzcat(A{:}),size(A,1),size(A,2),[]),[2 3 1])
Confirm that we have met the goal
isequal(B,BLoop)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!