コンマ区切りの数値、​テキスト混在のcsv​ファイルをTrueを​1.0、Falseを​0.0に読み替えた上​で読み込みFigur​eを表示したい

12 views (last 30 days)
添付の「Recive_Test.csv」は、数値・テキスト混在のファイルですが、「True・False」を「1.0・0.0」として読み込みFigureを表示したく、「Recive_Test.m」を作成したのですが、Workスペースの内容が「Recive_Test_0.png」の様に「NaN」となっていて「Recive_Test_1.png」の様に表示できません。
数値・テキスト混在のファイルを「True・False」を「1.0・0.0」として読み込む方法をご教示頂きたい。

Accepted Answer

Kojiro Saito
Kojiro Saito on 25 Feb 2025
文字列と数値の混合なので、一旦セルで読み込んでからTrueを1に、Falseを0に前処理する方法で実現できます。
以下がサンプルです。
filename = 'https://jp.mathworks.com/matlabcentral/answers/uploaded_files/1827064/Recive_Test.csv';
data = readcell(filename, Delimiter = ',');
%% 前処理
% Trueを1に、Falseを0にする
function out = myfunc(x)
if ischar(x)
out = str2double(replace(x, ["True", "False"], ["1", "0"]));
else
out = x;
end
end
% 前処理後にテーブルに変換する
data = cell2table(cellfun(@(x) myfunc(x), data, UniformOutput = false));
%% データ抽出
% 1列目の値が '374' のデータを抽出
data_374 = data(data{:, 1} == 374, :);
% 1列目の値が '1269' のデータを抽出
data_1269 = data(data{:, 1} == 1269, :);
%% fig1
figure()
ax(1)=subplot(4,1,1);
plot(data_1269,"Var2",["Var6","Var7"]);
legend(["Var6","Var7"],"Interpreter","none");
grid on
ax(2)=subplot(4,1,2);
plot(data_1269,"Var2",["Var16","Var17"]);
legend(["Var16","Var17"],"Interpreter","none");
grid on
ax(3)=subplot(4,1,3);
plot(data_1269,"Var2",["Var33","Var34"]);
legend(["Var33","Var34"],"Interpreter","none");
grid on
ax(4)=subplot(4,1,4);
plot(data_374,"Var2",["Var36","Var37"]);
legend(["Var36","Var37"],"Interpreter","none");
grid on
linkaxes(ax,'x');
  5 Comments
Kojiro Saito
Kojiro Saito on 26 Feb 2025
R2022bでは下記のようになります。
「コマンドウィンドウで選択を実行」では末尾のローカル関数が認識されないので、エディタータブの「実行」または「セクションの実行」、「実行して次に進む」のいずれかから実行する必要があります。
Recive_Test.m
%% データ読み込み
clc; clear
filename = 'Recive_Test.csv';
data = readcell(filename, Delimiter = ',');
%% 前処理
% Trueを1に、Falseを0にする
data = cell2table(cellfun(@(x) myfunc(x), data, UniformOutput = false));
%% データ抽出
% 1列目の値が '374' のデータを抽出
data_374 = data(data{:, 1} == 374, :);
% 1列目の値が '1269' のデータを抽出
data_1269 = data(data{:, 1} == 1269, :);
%% fig1
figure()
ax(1)=subplot(4,1,1);
plot(data_1269,"Var2",["Var6","Var7"]);
legend(["Var6","Var7"],"Interpreter","none");
grid on
ax(2)=subplot(4,1,2);
plot(data_1269,"Var2",["Var16","Var17"]);
legend(["Var16","Var17"],"Interpreter","none");
grid on
ax(3)=subplot(4,1,3);
plot(data_1269,"Var2",["Var33","Var34"]);
legend(["Var33","Var34"],"Interpreter","none");
grid on
ax(4)=subplot(4,1,4);
plot(data_374,"Var2",["Var36","Var37"]);
legend(["Var36","Var37"],"Interpreter","none");
grid on
linkaxes(ax,'x');
%% ローカル関数
function out = myfunc(x)
if ischar(x)
out = str2double(replace(x, ["True", "False"], ["1", "0"]));
else
out = x;
end
end
利元 河合
利元 河合 on 26 Feb 2025
ありがとうございました。
同じ結果になりました。
大変助かりました、ありがとうございます。

Sign in to comment.

More Answers (0)

Categories

Find more on データのインポートと解析 in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!