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

조회 수: 1 (최근 30일)
利元 河合
利元 河合 2025년 2월 24일
댓글: 利元 河合 2025년 2월 26일
添付の「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」として読み込む方法をご教示頂きたい。

채택된 답변

Kojiro Saito
Kojiro Saito 2025년 2월 25일
文字列と数値の混合なので、一旦セルで読み込んでから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
Kojiro Saito
Kojiro Saito 2025년 2월 26일
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
利元 河合
利元 河合 2025년 2월 26일
ありがとうございました。
同じ結果になりました。
大変助かりました、ありがとうございます。

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 データのインポートと解析에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!