Filter löschen
Filter löschen

Assign a numerical value based on the value of a string.

4 Ansichten (letzte 30 Tage)
Richard Nash
Richard Nash am 26 Sep. 2023
Kommentiert: Stephen23 am 26 Sep. 2023
I have data which contains a series of text strings. I have read this in from a CSV file.
The data can be thought of as "Good", "Better", "Best". I want to assign a numerical value to these so I can do some quantitative analysis.
I thought a good first step would be to create a vector with ['Good'; 'Better'; 'Best';] in and then a vector which is [1;2;3].
For each given isntance of "Good" in the data I could lookup the row ID in the first vector and then match to the row ID in the second vector.
But this feels clunky and in any case it seems you cannot put different length strings into each row of a vector - it returns
Error using vertcat
Dimensions of arrays being concatenated are not consistent.

Akzeptierte Antwort

Karl Cronburg
Karl Cronburg am 26 Sep. 2023
Bearbeitet: Karl Cronburg am 26 Sep. 2023
Fixed Set of Enumerated Strings
If the strings in the text file are known ahead-of-time, it may make sense to assign each string a numerical value and then compare against that value any time you need to check which string you have:
classdef Goodness
properties (Constant = true)
Good = 1;
Better = 2;
Best = 3;
end
end
And then parse your strings into the Goodness values:
function goodness = stringToGoodness(str)
switch str
case 'Good'
goodness = Goodness.Good;
case 'Better'
goodness = Goodness.Better;
case 'Best'
goodness = Goodness.Best;
end
end
Now you can do things like this elsewhere in your code to check which kind of goodness value you are looking at:
function processData(myData)
for idx = 1:numel(myData)
if myData(idx) == Goodness.Good
% My code for handling data that is good / OK.
elseif myData(idx) == Goodness.Better
% My code for handling data that is better than just 'good'.
end
end
end
Another option would be enums, although numeric literals will be more performant if your data set is large.
Key-Value Dictionary
Alternatively, instead of looking up the row ID in the first vector, you could use a dictionary like so:
dict = dictionary;
dict('Good') = 1;
dict('Better') = 2;
dict('Best') = 3;
if myData(5) == dict('Good')
% Code for 'good' data.
end

Weitere Antworten (0)

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by