Effacer les filtres
Effacer les filtres

Need help filling a Matrix with values from an 'fprintf' Command

1 vue (au cours des 30 derniers jours)
Jon Stapchuck
Jon Stapchuck le 24 Fév 2021
Commenté : Jon Stapchuck le 25 Fév 2021
Hello,
Basically I am computing several values and displaying them through each loop iteration using the 'fprintf'.
However, I would like to make the 'fprintf' output be in row i of a matrix, then after each loop, make this row the i+1 row, then continue this trend until a desired number of rows is reached. So my matrix will be of the size: k rows x size(fprintf) columns
Eventually, I would like to plot each individual row (which represents a velocity) vs its corresponding distance.
Here is the code I've been working on:
clc; clear all;
%Initial Guesses for Length and Num. of Grid Cells
L = 1;
m = 10;
IL = m+1;
Dx = L/m;
Dt = Dx/2;
%Initialize Vectors/Arrays
k = 10;
X = zeros(1,IL);
u = zeros(k,IL);
num = 100;
N = zeros(1,num);
%Set Grid Points for Given Range
for i=1:IL
X(i)=(i-1)*Dx;
end
for j=1:k
%Simplify the Initial Conditions
for i=1:IL
if (0<=X(i)) && (X(i)<=1)
u(j,i)=2-X(i);
elseif (X(i)>1)
u(j,i)=1;
else
u(j,i)=NaN;
end
end
%Generate Solution
for N=1:num
%Interior Points
for i=2:(IL-1)
u(j+1,i) = u(j,i)-Dt/Dx*u(j,i)*(u(j,i)-u(j,i-1));
end
%Boundary Points
u(j+1,IL) = 1;
u(j+1,1) = 2;
formatSpec = '%15.13f\n';
fprintf(formatSpec,u(j,i)) %I want to be able to use this output as a row-vector
%Go to next Time-Step
for i=1:IL
u(j,i) = u(j+1,i);
end
end
end
I tried just setting a variable to the 'fprintf', but that didn't work.
I can provide more details if need be.
Thanks,
Jon

Réponses (1)

Walter Roberson
Walter Roberson le 24 Fév 2021
Modifié(e) : Walter Roberson le 24 Fév 2021
variable = sprintf(formatSpec,u(j,i));
See also compose() . In particular, if you use a double-quoted format with compose() then the output is a string object.
formatSpec = "%15.13f\n";
variable = compose(formatSpec,u(j,i));
  3 commentaires
Walter Roberson
Walter Roberson le 25 Fév 2021
Both that sprintf() and that compose() are showing the entire vector. Notice you are passing u(j,i) with j and i both scalar, so the scalar so indexed is the entire vector you are asking to display.
Also, just before that you have
for i=2:(IL-1)
loop body
end
and when you have a for loop, the loop control variable will be left as the last variable it was assigned, so i will be left at the value IL-1 . That might not be what you were expecting.
Jon Stapchuck
Jon Stapchuck le 25 Fév 2021
Thank you, I forgot that when you helped me last time, that the i value leaves off at whatever it was last counted to.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by