필터 지우기
필터 지우기

cell2mat has a very specific condition

조회 수: 2 (최근 30일)
daniel slama
daniel slama 2022년 6월 20일
댓글: dpb 2022년 6월 20일
hey all! so i've been playing with cells and structures etc.
i have a structure 'students' with fields:name,id,grades.
in grades i have a nx1 cell array where n is the number of grades per students. the grades are in string and not numbers.
i wanted to calculate every student's avarage. i used a for loop and cell2mat and it gave me an nx2 matrix of char objects.
the problem is the last students, one of his grades is 100 which is 3 letters instead of 2 and because of that cell2mat has no idea how to compensate for it.
i know i could have made things easier for myself if i made a more normal structure in the first place but i'm too far in the excercise now lol.
any idea how to work with this?
  댓글 수: 2
DGM
DGM 2022년 6월 20일
Show us what code you have and provide an example of your data so that we can see what's going on.
daniel slama
daniel slama 2022년 6월 20일
of course, my bad.
this is my attempt to calculate every student's avarage with notes of what i tried to to every line.
[a b]=size(students)
for i = [1:1:b]
charmat=cell2mat(students(i).grades) %creates the nx2 matrix and gets stuck with the last student
[c d]=size(charmat)
nummat=[]
for x = [1:1:c]
temp=str2num(charmat(x,:)
nummat=[nummat ; temp] %makes a number matrix out of the char matrix
end
students(i).avarage=mean(nummat)
end

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

채택된 답변

dpb
dpb 2022년 6월 20일
Indeed, you made dereferencing the data about as hard as could by putting it into cell array -- a struct could/can hold an ordinary array; it shouldn't be too hard to change the code to make the grades arrays numeric to start with...but one way to your objective here is\
>> arrayfun(@(i)mean(str2double(students(i).grades)),1:numel(students),'UniformOutput',true)
ans =
84.0000 98.5000 86.1667 57.3333 87.2500
>>
  댓글 수: 2
daniel slama
daniel slama 2022년 6월 20일
this is incredible. i did mess up with the struct, guess i still need to work on that.
thank you so much!
dpb
dpb 2022년 6월 20일
Will become familiar idiom (along with the companion functions for cell arrays and sructure fields) with time...

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by