fork download
  1. function energy()
  2. % Clears command window, closes all figures, and clears workspace
  3. clc;
  4. close all;
  5. clear;
  6.  
  7. % Define the speed of light (c) in m/s
  8. c = 2.9979e8;
  9.  
  10. % Input: Mass vector from user
  11. m = input('Enter a vector of masses in kg: ');
  12.  
  13. % Ensure the input is a valid numeric vector
  14. if ~isnumeric(m) || isempty(m)
  15. error('Input must be a numeric vector.');
  16. end
  17.  
  18. % Compute energy values using E = mc^2
  19. E = m .* (c^2);
  20.  
  21. % Display results
  22. disp('Mass (kg) Energy (J)');
  23. disp([m(:), E(:)]);
  24.  
  25. % Save results to an Excel file
  26. filename = 'Energy_Data.xlsx';
  27. data = [m(:), E(:)];
  28. headers = {'Mass (kg)', 'Energy (J)'};
  29.  
  30. % Write headers and data to an Excel file
  31. writematrix(headers, filename, 'Sheet', 1, 'Range', 'A1');
  32. writematrix(data, filename, 'Sheet', 1, 'Range', 'A2');
  33.  
  34. % Plot energy vs mass (Standard plot)
  35. figure(1);
  36. plot(m, E, 'bo-', 'LineWidth', 2);
  37. xlabel('Mass (kg)');
  38. ylabel('Energy (J)');
  39. title('Energy vs Mass (Standard Plot)');
  40. grid on;
  41.  
  42. % Logarithmic plots in a single figure using subplots
  43. figure(2);
  44.  
  45. subplot(2,2,1);
  46. semilogx(m, E, 'r*-');
  47. xlabel('Mass (kg)');
  48. ylabel('Energy (J)');
  49. title('Semilogx: Log Scale on X-axis');
  50. grid on;
  51.  
  52. subplot(2,2,2);
  53. semilogy(m, E, 'g*-');
  54. xlabel('Mass (kg)');
  55. ylabel('Energy (J)');
  56. title('Semilogy: Log Scale on Y-axis');
  57. grid on;
  58.  
  59. subplot(2,2,3);
  60. loglog(m, E, 'm*-');
  61. xlabel('Mass (kg)');
  62. ylabel('Energy (J)');
  63. title('Loglog: Log Scale on Both Axes');
  64. grid on;
  65.  
  66. % Adjust subplot layout for better visualization
  67. subplot(2,2,4);
  68. text(0.1, 0.5, 'Logarithmic Analysis of Energy vs Mass', 'FontSize', 12, 'FontWeight', 'bold');
  69. axis off;
  70.  
  71. % Notify user about file storage
  72. fprintf('Energy values have been saved to %s\n', filename);
  73.  
  74. % Sample Output
  75. fprintf('\nSample Output:\n');
  76. fprintf('Enter a vector of masses in kg: [1 5 10 50 100]\n');
  77. fprintf('\nMass (kg) Energy (J)\n');
  78. sample_m = [1 5 10 50 100];
  79. sample_E = sample_m .* (c^2);
  80. fprintf('%-12.4f %-12.4e\n', [sample_m; sample_E]);
  81. fprintf('\nEnergy values have been saved to Energy_Data.xlsx\n');
  82. end
  83.  
Success #stdin #stdout 0.1s 46988KB
stdin
Standard input is empty
stdout
Standard output is empty