Add to a cell array in a for loop

6 次查看(过去 30 天)
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

回答(1 个)

Star Strider
Star Strider 2019-4-1
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 个评论
Camden Ford
Camden Ford 2019-4-1
Thanks for the help but the problem I am still having is that there are multiple majors that have the same salaries top5salary_nstem75_stem25. In my code I want to add all the majors that share the same salary that is in the top 5 (for example 70,000 has several majors that meet the logic statement) but my cell array is only storing the last iterations. I want to keep track of all the majors that meet this requirement. How do I add strings for all of these majors to the cell array top5majors_nstem75_stem25in a for loop?
Star Strider
Star Strider 2019-4-1
编辑:Star Strider 2019-4-2
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by