Borrar filtros
Borrar filtros

how to store total numbers from for loop in variables

9 visualizaciones (últimos 30 días)
Methat
Methat el 18 de Abr. de 2024
Respondida: Gyan Vaibhav el 18 de Abr. de 2024
I want to create a for if loop that checks if a number is less than or greater than certain values from an excel spreadsheet and then calculates the total amount and assigns that total to a variable.
Here is a small snipit of the current code I have wrote how would I be able to count the grade of anything below 50 in the excel spreadsheet and then take that toal and assign it to the variable fa.
x = xlsread('grades.xlsx');
% Initialise all variables to zero
fa = 0;
pa = 0;
cr = 0;
di = 0;
hd = 0;
% Write your code here to count the number of each grade contained in 'x'
for k = 1:length(x)
if x(k) < 50
fa = fa + x(k);
else
end
end
  2 comentarios
Walter Roberson
Walter Roberson el 18 de Abr. de 2024
That code already totals grades less than 50 and assigns the total to the variable fa
Methat
Methat el 18 de Abr. de 2024
I see so that was already working by removing the ; i can see the output is there a way to have it in a more readable output?
fa =
15
fa =
57
and it keeps going, is there a way display it in a more clearly output.

Iniciar sesión para comentar.

Respuesta aceptada

Gyan Vaibhav
Gyan Vaibhav el 18 de Abr. de 2024
Hi Methat,
MATLAB is very capable of working with vectors and matrices. You can do these counts without a for loop, using vector operations and logical indexing.
Further if you want to print these variables to the command line, you can use the "disp" or "fprintf" methods. Removing the semi-colon just displays the variable to the command line.
Change the initialization to the following and it does the same task, using the logical indexing.
fa = sum(x < 50);
fprintf('fa count: %d\n', fa);
Sample:
%let's define a sample x, say
x = [25, 40 , 90 , 24, 89, 72, 61, 97];
fa = sum(x < 50); % Counts grades less than 50
% Print variables to verify
fprintf('fa count: %d\n', fa);
fa count: 3
Look at these documentation pages about printing and logical indexing in MATLAB.
Hope this helps.
Thanks
Gyan

Más respuestas (1)

KSSV
KSSV el 18 de Abr. de 2024
x = xlsread('grades.xlsx');
% Initialise all variables to zero
fa = 0;
pa = 0;
cr = 0;
di = 0;
hd = 0;
% Write your code here to count the number of each grade contained in 'x'
fa = zeros(1,[]) ;
count = 1 ;
fa(count) = 0 ;
for k = 1:length(x)
if x(k) < 50
count = count+1 ;
fa(count) = fa(count-1) + x(k);
else
end
end

Categorías

Más información sobre Data Export to MATLAB en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by