Is there a one-line code for this?
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mitsu
le 27 Juin 2021
Commenté : Dyuman Joshi
le 20 Nov 2025 à 15:49
% I would like to go from A = [1 1;2 2;3 3;4 4;5 5]
% to A = [1 1;2 2;3 3;4 4;5 5;1 2;2 3;3 4;4 5;5 6];
A = [1 1;2 2;3 3;4 4;5 5];
% Multi-line approach
B = A;
B(:,2) = B(:,2) + 1;
A = [A;B];
clear B
% Is there a way to do this in one line of code? I have to do similar operations multiple times,
% and would like to know if there is a way to do so. Otherwise, I will settle for a function.
% Note that the actual matrices are 1,000,000+ x 30 in size.
% Thank you
0 commentaires
Réponse acceptée
Stephen23
le 27 Juin 2021
A = [1 1;2 2;3 3;4 4;5 5];
A = [A;A+(0:1)]
3 commentaires
Stephen23
le 27 Juin 2021
"the simplest way is the following then?"
Probably the "simplest way" is just as you show in your question.
If you want to avoid duplicated data, you could create B first then add one to the appropriate (part-)column.
Plus de réponses (1)
SUPRIYA
le 20 Nov 2025 à 7:28
Modifié(e) : Stephen23
le 20 Nov 2025 à 9:15
% Define the differential equation dy/dx = f(x, y)
% Example: dy/dx = (y^2-x^2)/(y^2+x^2) f = @(x, y) x + y;
% Input initial and final conditions
x0 = input('Enter the initial value of x0: ');
y0 = input('Enter the initial value of y0: ');
xg = input('Enter the final value of xg: ');
h = input('Enter the value of step size h: ');
% Number of steps
n = (xg - x0) / h;
% Runge-Kutta 2nd order iteration
for i = 1:n
k1 = h * f(x0, y0);
k2 = h * f(x0 + h, y0 + k1);
k = (k1 + k2) / 2;
yg = y0 + k; % Update y
x0 = x0 + h; % Update x y0=yg;
end
% Display final result
fprintf('The final value of y at x = %f is y = %f\n', x0, y0);
Is there a way to do entire code in one line
2 commentaires
Stephen23
le 20 Nov 2025 à 9:17
"Is there a way to do entire code in one line"
x0 = input('Enter the initial value of x0: '); y0 = input('Enter the initial value of y0: '); xg = input('Enter the final value of xg: '); h = input('Enter the value of step size h: '); n = (xg - x0) / h; for i = 1:n; k1 = h * f(x0, y0); k2 = h * f(x0 + h, y0 + k1); k = (k1 + k2) / 2; yg = y0 + k; x0 = x0 + h; y0=yg; end; fprintf('The final value of y at x = %f is y = %f\n', x0, y0);
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!