WICHTIG: Der Betrieb von goMatlab.de wird privat finanziert fortgesetzt. - Mehr Infos...

Mein MATLAB Forum - goMatlab.de

Mein MATLAB Forum

 
Gast > Registrieren       Autologin?   

Partner:




Forum
      Option
[Erweitert]
  • Diese Seite per Mail weiterempfehlen
     


Gehe zu:  
Neues Thema eröffnen Neue Antwort erstellen

Datainame als Variablenname verwenden und weiter verarbeiten

 

JaSoIstEs
Forum-Guru

Forum-Guru


Beiträge: 266
Anmeldedatum: 01.10.12
Wohnort: Hessen
Version: 2019b
     Beitrag Verfasst am: 25.07.2018, 09:05     Titel: Datainame als Variablenname verwenden und weiter verarbeiten
  Antworten mit Zitat      
Guten Morgen,

Ich hab hier einen code geschrieben damit ich CSV-Dateien einlesen kann.
Das funktioniert auch alles tadellos.
Da ich das ganze aber umschreiben muss um mehrere Dateien laden will um evtl. Vergleiche ziehen zu können, hatte ich die Idee das ich den Namen aus dem uigetfile nehme ihn als legitimem Namen umwandle und dann als Variablenname weiter verwende.
Ich scheitere aber daran das ich den Namen "automatisiert" weiter verwenden kann.
Er steht dann im Workspace will ihn aber nutzen ohne den Namen direkt einzugeben.
Wie mache ich das? Hat da jemand eine Idee?

Danke euch vielmals im Voraus.

Code:

%% Import data from text file.
% Script for importing data from the following text file:
%
% To extend the code to different selected data or a different text file,
% generate a function instead of a script.

%% Initialize variables.
[file,path] = uigetfile('*.mdf');
filename = file(1:end-4);
N = matlab.lang.makeValidName(filename);
assignin('base', N, [])
delimiter = '\t';
endRow = 15;

%% Read columns of data as text:
% For more information, see the TEXTSCAN documentation.
formatSpec = '%*s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';

%% Open the text file.
fileID = fopen([path,file],'r');

%% Read columns of data according to the format.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow, 'Delimiter', delimiter, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');

%% Close the text file.
fclose(fileID);

%% Convert the contents of columns containing numeric text to numbers.
% Replace non-numeric text with NaN.
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
    raw(1:length(dataArray{col}),col) = mat2cell(dataArray{col}, ones(length(dataArray{col}), 1));
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));

for col=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
    % Converts text in the input cell array to numbers. Replaced non-numeric
    % text with NaN.
    rawData = dataArray{col};
    for row=1:size(rawData, 1)
        % Create a regular expression to detect and remove non-numeric prefixes and
        % suffixes.
        regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\.]*)+[\,]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\.]*)*[\,]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
        try
            result = regexp(rawData(row), regexstr, 'names');
            numbers = result.numbers;
           
            % Detected commas in non-thousand locations.
            invalidThousandsSeparator = false;
            if numbers.contains('.')
                thousandsRegExp = '^\d+?(\.\d{3})*\,{0,1}\d*$';
                if isempty(regexp(numbers, thousandsRegExp, 'once'))
                    numbers = NaN;
                    invalidThousandsSeparator = true;
                end
            end
            % Convert numeric text to numbers.
            if ~invalidThousandsSeparator
                numbers = strrep(numbers, '.', '');
                numbers = strrep(numbers, ',', '.');
                numbers = textscan(char(numbers), '%f');
                numericData(row, col) = numbers{1};
                raw{row, col} = numbers{1};
            end
        catch
            raw{row, col} = rawData{row};
        end
    end
end


%% Replace non-numeric cells with NaN
R = cellfun(@(x) ~isnumeric(x) && ~islogical(x),raw); % Find non-numeric cells
raw(R) = {NaN}; % Replace non-numeric cells

%% Create output variable
filename = table;
filename.Torque1cNm = cell2mat(raw(:, 1));
filename.Speed1RPM = cell2mat(raw(:, 2));
filename.WattsOUT1 = cell2mat(raw(:, 3));
filename.Volts1 = cell2mat(raw(:, 4));
filename.Amps1 = cell2mat(raw(:, 5));
filename.WattsIN1 = cell2mat(raw(:, 6));
filename.Volts2 = cell2mat(raw(:, 7));
filename.Volts3 = cell2mat(raw(:, 8));
filename.Volts4 = cell2mat(raw(:, 9));
filename.VoltsSumA = cell2mat(raw(:, 10));
filename.Amps2 = cell2mat(raw(:, 11));
filename.Amps3 = cell2mat(raw(:, 12));
filename.Amps4 = cell2mat(raw(:, 13));
filename.AmpsSumA = cell2mat(raw(:, 14));
filename.WattsINSumA = cell2mat(raw(:, 15));
filename.EfficiencyElect = cell2mat(raw(:, 16));
filename.EfficiencySumA = cell2mat(raw(:, 17));
filename.Efficiency1 = cell2mat(raw(:, 18));
filename.Frequency1 = cell2mat(raw(:, 19));
filename.U1 = cell2mat(raw(:, 20));
filename.I1 = cell2mat(raw(:, 21));
filename.PHI1 = cell2mat(raw(:, 22));

%% Clear temporary variables
clearvars N delimiter endRow formatSpec fileID dataArray ans raw col numericData rawData row regexstr result numbers invalidThousandsSeparator thousandsRegExp R;
 
Private Nachricht senden Benutzer-Profile anzeigen


JaSoIstEs
Themenstarter

Forum-Guru

Forum-Guru


Beiträge: 266
Anmeldedatum: 01.10.12
Wohnort: Hessen
Version: 2019b
     Beitrag Verfasst am: 25.07.2018, 09:53     Titel:
  Antworten mit Zitat      
Jetzt habe ich es zumindest geschafft mit Hilfe von:

Code:

eval([N '=table']);
 


die Tabelle mit dem richtigen Variablennamen zu verwenden.

wenn ich aber nun:

Code:

eval([N,'.Torque1cNm = cell2mat(raw(:,1)']);
 


Bekomme ich den folgenden Fehler:
Error: This statement is incomplete.
Private Nachricht senden Benutzer-Profile anzeigen
 
Jan S
Moderator

Moderator


Beiträge: 11.057
Anmeldedatum: 08.07.10
Wohnort: Heidelberg
Version: 2009a, 2016b
     Beitrag Verfasst am: 25.07.2018, 12:49     Titel: Re: Datainame als Variablenname verwenden und weiter verarbe
  Antworten mit Zitat      
Hallo JaSoIstEs,

Zitat:
...will um evtl. Vergleiche ziehen zu können, hatte ich die Idee das ich den Namen aus dem uigetfile nehme ihn als legitimem Namen umwandle und dann als Variablenname weiter verwende.


Das ist eine ausgesprochen schlechte Idee. Ich rate dringend davon ab, den das Gefrickel mit eval ist bekannt dafür, dass Du Dir mehr Probleme schaffst als löst. Es gibt hunderte Threads zu diesem Thema im Forum.

Das dynamische Erzeugen von Variablen bremst Matlab enorm aus - Faktor 100 ist möglich, und es macht das Debuggen extrem viel schwieriger, wenn nicht unmöglich. Deswegen sind eval , assignin und ihre Geschwister Methoden um sich ins Knie zu bohren und es gibt immer eine bessere Lösung.

Stattdessen könntest Du die Tabellen als Felder eines Structs speichern:
Code:

Das ist sauber und effizient.

Nebenbei: "path" ist ein wichtiger Matlab-Befehl. Ihn mit einer Variable zu überschreiben kann zu sehr verwirrenden Effekten führen. Besser: "pathname". Das gleiche gilt für "table".

Gruß, Jan
Private Nachricht senden Benutzer-Profile anzeigen
 
Neues Thema eröffnen Neue Antwort erstellen



Einstellungen und Berechtigungen
Beiträge der letzten Zeit anzeigen:

Du kannst Beiträge in dieses Forum schreiben.
Du kannst auf Beiträge in diesem Forum antworten.
Du kannst deine Beiträge in diesem Forum nicht bearbeiten.
Du kannst deine Beiträge in diesem Forum nicht löschen.
Du kannst an Umfragen in diesem Forum nicht mitmachen.
Du kannst Dateien in diesem Forum posten
Du kannst Dateien in diesem Forum herunterladen
.





 Impressum  | Nutzungsbedingungen  | Datenschutz | FAQ | goMatlab RSS Button RSS

Hosted by:


Copyright © 2007 - 2024 goMatlab.de | Dies ist keine offizielle Website der Firma The Mathworks

MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, SimBiology, SimHydraulics, SimEvents, and xPC TargetBox are registered trademarks and The MathWorks, the L-shaped membrane logo, and Embedded MATLAB are trademarks of The MathWorks, Inc.