Control Dynamically Multi-Dimension Matrix on fprintf

7 Ansichten (letzte 30 Tage)
Merih Dikbas
Merih Dikbas am 10 Mai 2021
Kommentiert: Merih Dikbas am 10 Mai 2021
Hi, I have 3x3x3 array and I can print elements on txt like this:
A(:,:,1)=[1 2 4 ; 5 2 1 ; 6 2 1];
A(:,:,2)=[4 6 1 ; 8 0 3 ; 1 2 4];
A(:,:,3)=[5 8 2 ; 4 4 4 ; 1 0 0];
function PrintArray(A)
MyText=fopen('Text1.txt','wt');
for i=1:size(A,1)
for j=1:size(A,2)
for k=1:size(A,3)
PrintedVal=A(i,j,k);
fprintf(MyText,'A(%d,%d,%d) = %d \n',i,j,k,PrintedVal) ;
end
end
end
fclose(MyText);
end
I am looking for a script that it will automatically detect the number of dimensions, will be able to perform in 2D or 4D.
Thanks for helping.

Akzeptierte Antwort

Stephen23
Stephen23 am 10 Mai 2021
Bearbeitet: Stephen23 am 10 Mai 2021
A(:,:,1) = [1,2,4;5,2,1;6,2,1];
A(:,:,2) = [4,6,1;8,0,3;1,2,4];
A(:,:,3) = [5,8,2;4,4,4;1,0,0];
D = ndims(A);
F = repmat(',%d',1,D);
F = sprintf('A(%s) = %%d\n',F(2:end));
C = cell(1,D);
for k = 1:numel(A)
[C{:}] = ind2sub(size(A),k);
fprintf(F,C{:},A(k))
end
A(1,1,1) = 1 A(2,1,1) = 5 A(3,1,1) = 6 A(1,2,1) = 2 A(2,2,1) = 2 A(3,2,1) = 2 A(1,3,1) = 4 A(2,3,1) = 1 A(3,3,1) = 1 A(1,1,2) = 4 A(2,1,2) = 8 A(3,1,2) = 1 A(1,2,2) = 6 A(2,2,2) = 0 A(3,2,2) = 2 A(1,3,2) = 1 A(2,3,2) = 3 A(3,3,2) = 4 A(1,1,3) = 5 A(2,1,3) = 4 A(3,1,3) = 1 A(1,2,3) = 8 A(2,2,3) = 4 A(3,2,3) = 0 A(1,3,3) = 2 A(2,3,3) = 4 A(3,3,3) = 0

Weitere Antworten (0)

Kategorien

Mehr zu Linear Algebra 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!

Translated by