Help with importing data from Excel

1 visualización (últimos 30 días)
A
A el 8 de Mayo de 2023
Comentada: Image Analyst el 14 de Feb. de 2025
First of all say that it is my first time posting here and that my native language is not English, so I don't know if I express myself rigorously enough.
I have this code that has to import responses from an Excel file of a multiple choice exam. The problem is that when passing the character string from excel to matlab, if the character string has a blank space at the beginning, MATLAB suppresses it.
I leave the code of the main program:
clear;
clc;
%Solicitar al usuario la extension deseada en los archivos .xls o .xlsx
formato = input('Introduce el formato de los archivos: ', 's');
clc;
% solicitar al usuario que introduzca el nombre del archivo original
archivooriginal = strcat(input('Introduce el nombre del archivo original: ', 's'), formato);
archivonuevo = strcat(input('Introduce el nombre del archivo final: ', 's'), formato);
archivocorreccion = strcat(input('Introduce el nombre del archivo de correccion: ', 's'), formato);
% duplicar el archivo de Excel
copyfile(archivooriginal, archivonuevo);
% cargar excel
respuestasalumnos = readtable(archivonuevo,"Format", "auto");
correccion = readtable(archivocorreccion);
...
for i = 1:size(resp,1)
type = str2double(tipex(i));
%cambiamos espacio por X
cadena0 = strrep(char(resp(i)), ' ', 'X');
cadena1 = char(correc(type,:));
% añadir x al final de cadena1 hasta que tenga la misma longitud
while length(cadena0) < length(cadena1)
cadena0 = [cadena0 'X'];
end
% Guardar los cambios en la tabla respuestasalumnos
respuestasalumnos{i, col_resp} = {cadena0};
...
The problem is that these data are needed later in a secondary program that compares the answers of the students with the answers of the solutions, but of course, if the leading blank space is deleted, all the answers are moved one position (In case of that only one answer was left at the beginning without answering) and therefore it does not correct the answers well.
I leave the code of the program in which the scores are calculated in case it also helps to determine a solution:
function Calcularrespuestas(respuestasalumnos,correccion,archivonuevo)
% declaracion de parametros de correccion
pfallo = 0.25;
pblanco = 0.0;
clc;
...
% recorrer la segunda columna de la matriz
for i = 1:size(resp,1)
type = str2double(tipex(i));
%cambiamos espacio por X
cadena0 = char(resp(i));
cadena1 = char(correc(type,:));
% inicializar contadores
aciertos = 0;
fallos = 0;
enblanco = 0;
%calcular similitud
for j = 1:length(cadena0)
if j <= length(cadena1)
if cadena0(j) == cadena1(j)
aciertos = aciertos + 1;
elseif cadena0(j) == 'X'
enblanco = enblanco + 1;
else
fallos = fallos + 1;
end
end
end
%calcular nota
nota = aciertos - fallos*pfallo - enblanco*pblanco;
...
I also attached a screenshot of the excel file to denote the blank spaces I commented on:

Respuestas (2)

Image Analyst
Image Analyst el 8 de Mayo de 2023
Evidently readtable is calling strtrim internally according to your description of its behavior. If you want the space to remain in the front, then try readcell instead of readtable.
If you have any more questions, then attach your Excel workbook and code to read it in with the paperclip icon after you read this:

BERNARDO ELEMBO WILASI
BERNARDO ELEMBO WILASI el 13 de Feb. de 2025
Editada: Walter Roberson el 14 de Feb. de 2025
%I need to improve this code:
%%Cálculo de probabilidades a partir de un juicio de expertos.
clear
clc
file='juicioexp.xlsx'; %archivo .xlsx con la información del juicio de expertos
data=importdata(file);
data(1,:)=[]; %borrado de la primera fila del archivo
%Cálculo de la ponderación. Primera columna correspondiente con el puesto de trabajo
for y=1:length(data(:,2))
if strcmpi(data(y,2),'Worker/Officer')==1
P(y,1)=3;
else
if strcmpi(data(y,2),'Engineer/Lead Engineer')==1
P(y,1)=4;
else
if strcmpi(data(y,2),'Professor/Senior Manager')==1
P(y,1)=5;
end
end
end
end
%Cálculo de la ponderación. Segunda columna correspondiente con la
%experiencia en años
y=1;
for y=1:length(data(:,2))
if strcmpi(data(y,3),'<5')==1
P(y,2)=1;
else
if strcmpi(data(y,3),'5-10')==1
P(y,2)=2;
else
if strcmpi(data(y,3),'10-20')==1
P(y,2)=3;
else
if strcmpi(data(y,3),'20-30')==1
P(y,2)=4;
else
if strcmpi(data(y,3),'>30')==1
P(y,2)=5;
end
end
end
end
end
end
%Cálculo de la ponderación. Tercera columna correspondiente con el nivel de
%educación
y=1;
for y=1:length(data(:,2))
if strcmpi(data(y,4),'Graduate')==1
P(y,3)=1;
else
if strcmpi(data(y,4),'Technical')==1
P(y,3)=2;
else
if strcmpi(data(y,4),'Bachelors')==1
P(y,3)=3;
else
if strcmpi(data(y,4),'Masters')==1
P(y,3)=4;
else
if strcmpi(data(y,4),'Doctoral')==1
P(y,4)=5;
end
end
end
end
end
end
pref=[10 10 4]; %indica la preferencia que se le quiere dar a las distitnas columnas de ponderación
P2=sum((P.*pref)')'; %el peso total de cada experto sumando las tres columnas de ponderación
pond=(P2)/sum(P2); %el peso de cada experto en tanto por 1
data(:,1:5)=[]; %borrado de las columnas que ya no se van a usar
BE=(1:length(data(1,:))); %número de eventos básicos
for s=1:length(data(1,:)) % Matriz de relación R entre expertos y BE
%Las columnas son los BE y las filas los expertos
for l=1:length(data(:,1))
if strcmpi(data(l,s),'Very low')==1
R(l,s)=1;
else
if strcmpi(data(l,s),'Low')==1
R(l,s)=2;
else
if strcmpi(data(l,s),'Medium')==1
R(l,s)=3;
else
if strcmpi(data(l,s),'High')==1
R(l,s)=4;
else
if strcmpi(data(l,s),'Very high')==1
R(l,s)=5;
end
end
end
end
end
end
end
x=(0:0.01:1);
% VH = trapmf(x, [0.8 0.9 1.1 1.2]); %Funciones de membresía triangulares
% H= trimf(x, [0.6 0.75 0.9]);
% M= trimf(x, [0.3 0.5 0.7]);
% L= trimf(x, [0.1 0.25 0.4]);
%VL= trapmf(x, [-0.2 -0.1 0.1 0.2]);
%VH = gaussmf(x, [0.1062 1] ); %Funciones de membresía gaussianas
%H= gaussmf(x, [0.1062 0.75]);
%M= gaussmf(x, [0.1062 0.5]);
%L= gaussmf(x, [0.1062 0.25]);
%VL= gaussmf(x, [0.1062 0]);
%mf=[VL; L; M; H; VH];
for i=1:length(R(1,:))
for k=1:length(R(:,1))
mfBE(:,k)=mf(R(k,i),:); %funciones de membresía para cada uno de los BE dadas por los expertos (columnas)
t(:,k)=mfBE(:,k)*pond(k); %cada columna de mfBE es cada experto, t será mfBE por la ponderación de cada experto
end
%mean_BE(:,i)=mean(t'); %agregación de las funciones de membresía mediante la media aritmética
mean_BE(:,i)=sum(t'); %agregación de las mf usando la suma de todas ellas
deffBE(i) = defuzz(x, mean_BE(:,i), 'centroid'); %deffuzificación usando el centroide
consenso(i)=max(mean_BE(:,i)); %medición del consenso a partir del máximo de la función de membresía
consenso2(i)=defuzz( mean_BE(:,i),x, 'centroid'); %medición del consenso a partir del centro de masas (coordenada vertical)
suma=0;
for j=2:length(x)-1
suma=suma+mean_BE(j,i);
end
consenso3(i)=(x(2)-x(1))/2*(mean_BE(1,i)+2*suma+mean_BE(length(x),i))/x(length(x));
end
%Gráficas
figure(1), figure(clf)
for c=1:length(BE)
subplot(5,round(length(BE)/5),c)
plot(x,mean_BE(:,c),deffBE(c),consenso3(c),'o')
axis([0 max(x) 0 round(max(max(mean_BE))+0.05,1)]) %para fijar los ejes de las gráficas
s1='Evento básico ' ;
s2= num2str(c);
s = strcat(s1,{' '},s2);
xlabel(s)
grid on
grid minor
end
%Defuzz para cada BE
figure(2), figure(clf)
plot(BE,deffBE,'-o')
xlabel('Evento básico')
ylabel('Defuzzyficación')
grid on
grid minor
figure(3), figure(clf)
plot(BE,consenso3)%consenso es el max, consenso 2 es el centroide en el eje Y,
xlabel('Evento básico')
ylabel('Nivel de consenso')
grid on
grid minor
figure (4), figure(clf)
plot(x,mf)
title('Funciones de membresía')
grid on
grid minor
  1 comentario
Image Analyst
Image Analyst el 14 de Feb. de 2025
Not sure how this is an answer to @A's code. Please explain.

Iniciar sesión para comentar.

Categorías

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

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by