How to loop through each row of a column, then loop through the remaining columns?
72 次查看(过去 30 天)
显示 更早的评论
Hi all, I am very new to coding and MATLAB, so please bear with me here:
I have a large spreadsheet of data that I have divided into separate groups (i.e., group 1 = data(:, 1:3), group 2 = data(:, 4:5), and so forth. Each data point is a textual response (e.g., "apple"), which I want to convert to a corresponding numeric response (e.g., "0" for "apple").
I have created a function for the text to number conversion, which I would like to iterate through each row of a column, then repeat for a certain number of columns (i.e., for group 1, I would repeat this procedure from column 1 to column 3).
My current code achieves this for column 1, but repeats the column 1 output in column 2 and 3 (instead of converting the ACTUAL text responses in column 2 and 3).
How can I fix this so that the code properly converts each column? Thank you so much in advance.
group1_responses = data(:,1:3);
[rows, cols] = size(group1_responses);
group1_values = zeros(rows, cols);
for i = 1:cols
for j = 1:rows
response = group1_responses{j};
group1_values(j, i) = group1_text_to_val(response);
end
end
function [val] = group1_text_to_val(text)
if text == "apple"
val = 0;
elseif text == "banana"
val = 1;
elseif text == "orange"
val = 2;
elseif text == "grape"
val = 3;
elseif text == "pear"
val = 4;
else
val = NaN;
end
end
0 个评论
采纳的回答
更多回答(2 个)
Matt J
2022-5-24
编辑:Matt J
2022-5-24
If your group1_responses is a cell or string array, there is no need to distinguish between rows and columns at all. Just do,
group1_responses={'apple', 'banana';'orange','grape';'pear','pineapple'}
group1_values=zeros(size(group1_responses));
for k = 1:numel(group1_values)
group1_values(k) = group1_text_to_val(group1_responses{k});
end
group1_values
0 个评论
Jon
2022-5-24
It's a little hard to tell without having the values for your matrix data to try this with, but it looks like you should modify your assignment of response to
response = group1_responses(i,j);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!