Hi! I have gotten a data file which contains 57 different "keys" like 'XPOS' (x-position), YPOS (y-position), etc. Within these "keys" the data is stored in arrays. I want to ask the user "which dataset do you want to work with" and thus use this input in further calcualtions. I approached this in the same way I would in Python, but I have not gotten a usable result. My current code is attached.
For information, I would like the user to write "XPOS" as input.
The error I get is at the bottom of the code.
Thank you in advance!
data = load('x.mat');
name = input('Which dataset do you wanna work with? ','s');
if isempty(name)
reply = 'Y';
end
pos = data.name;
plot(data.Time,pos); %Just a simple plot of position against time
%%%%%% Mean, max, min calc %%%%%%
Mean = mean(pos);
Max = max(pos);
Min = min(pos);
Column = [['Max_ : ', num2str(Max)];['Min_ : ', num2str(Min)];['Mean : ', num2str(Mean)]];
disp(Column);
%%% MY ERROR %%%
Reference to non-existent field 'name'.
Error in plotter (line 20)
pos = data.name;

 채택된 답변

Walter Roberson
Walter Roberson 2021년 6월 22일

0 개 추천

if ~isfield(data, 'name')
error('dataset "%s" is not loaded', name)
end
pos = data.(name);

댓글 수: 3

Thank you for the respons.
When I try with you code, I get the error "dataset "%s" is not loaded". The problem is that it should be. When I manually use data.XPOS, everything runs smoothly, but when using pos = data.(name), it seems that it don't recognize XPOS.
For information, I have tried to calculate the mean (just for testing) as follows:
Mean = mean(pos);
Walter Roberson
Walter Roberson 2021년 6월 24일
편집: Walter Roberson 2021년 6월 24일
if ~isfield(data, name)
error('dataset "%s" is not loaded', name)
end
pos = data.(name);
If data.XPOS works but name = 'XPOS'; data.(name) does not work, then please show
fn = fieldnames(data);
if ismember(name, fn)
fprintf('field "%s" IS found as a field name\n', name);
else
fprintf('field "%s" is NOT found as a field name\n\n', name);
for K = 1 : length(fn)
thisfield = fn{K};
fprintf('field #%d is %d characters long "%s". chars are: ', K, length(thisfield), thisfield);
fprintf('%s\n\n', mat2str(double(thisfield)));
end
end
This is intended as debugging code. It might, for example, help you through a situation where the stored field name turns out to be XP0S instead of XPOS
Vilde Solberg
Vilde Solberg 2021년 6월 24일
Thank you!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Environment and Settings에 대해 자세히 알아보기

질문:

2021년 6월 22일

댓글:

2021년 6월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by