Add to a cell array in a for loop
6 views (last 30 days)
Show older comments
Hi,
So am trying to figure out how to add values to a cell array in a for loop. Basically, I am analyzing college major data from the ACS and wanted to determine what majors had salaries that were in the 75th percentile of non-STEM fields but the 25th percentile of STEM fields. I then found the top 5 salaries given these conditions and am now trying to figure out how to figure out which majors correspond to those salaries. I have a for loop that runs though all the majors and checks to see if that major has a 25th percentile or 75th percentile salary that is in the top 5. The problem is that there are more than one majors that share the salary in the top 5. So I need my cell array to store each major that corresponds to the salary. Here are the lines from the code I am trying to get to work:
for j = 1:length(majors)
indx = find(top5salary_nstem75_stem25==P25(j)|P75(j));
top5majors_nstem75_stem25(indx) = majors(indx); % need this to store multiple cells for each major that satisfies logic
end
0 Comments
Answers (1)
Star Strider
on 1 Apr 2019
Your ‘indx’ assignment is not coded correctly. See the documentation section on Apply Multiple Conditions (link).
This may work better:
indx = find(top5salary_nstem75_stem25==P25(j) | top5salary_nstem75_stem25==P75(j));
I can’t run your code.
4 Comments
Star Strider
on 1 Apr 2019
Edited: Star Strider
on 2 Apr 2019
I’m not certain what you’re referring to.
Try this:
for j = 1:length(majors)
indx{j,:} = find(top5salary_nstem75_stem25==P25(j) | top5salary_nstem75_stem25==P75(j));
% top5majors_nstem75_stem25(indx) = majors(indx);
end
idx = unique([indx{:}]);
top5majors_nstem75_stem25(idx) = majors(idx);
There are only five, those being 1, 2, 3, 4, and 8.
EDIT — (1 Apr 2019 at 00:49)
I was primarily concerned with the logic of your find call, so I didn’t look much further through your code. The only other possibility is to use the ismember (link) or ismembertol function instead of find and the loop.
I have no other suggestions.
See Also
Categories
Find more on Elementary Math 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!