A beginners question on reading matrix array
Afficher commentaires plus anciens
I'm learning MATLAB out of curiosity, without any prior programming experience. I'm having an issue with a simple matrix array.
What_to_Wear
%
% out1 = What_to_wear({'pants','scarf','heels','shoes'; true,false,true,true; true,true,false,true})
% out1 => ['You should wear the pants and/or shoes, but DO NOT wear the scarf or heels.']
%
So, my array is
Pants scarf heels shoes true false true true true true false true
when R2C1 = R3C1 = True, True - then yes to "pants" else no.
Similarly, when R2C3=R3C3 True, True then yes to shoes.
In other words when row 2 and row 3 are both true, you should wear the item in row 1, otherwise you should not wear the item in row 1.
I hope I was able to clearly present the problem.
Thanks in advance.
Réponses (3)
Image Analyst
le 13 Oct 2015
0 votes
How about this:
ca = cell({'pants','scarf','heels','shoes'; true,false,true,true; true,true,false,true})
for col = 1 : size(ca, 2)
if ca{2, col} & ca{3, col}
fprintf('You should wear the %s.\n', ca{1, col});
else
fprintf('You should not wear the %s.\n', ca{1, col});
end
end
gives:
ca =
'pants' 'scarf' 'heels' 'shoes'
[ 1] [ 0] [ 1] [ 1]
[ 1] [ 1] [ 0] [ 1]
You should wear the pants.
You should not wear the scarf.
You should not wear the heels.
You should wear the shoes.
C = {'pants','scarf','heels','shoes'; true,false,true,true; true,true,false,true};
% Index of where both lines are true:
idx = all(cell2mat(C(2:3,:)),1);
X(2,:) = C(1,idx); % clothes for true
Y(2,:) = C(1,~idx); % clothes for false
% Add punctuation:
X(1,:) = {', '};
Y(1,:) = {', '};
X{1,end} = ' and/or ';
Y{1,end} = ' or ';
% Create output string:
fmt = 'You should wear the %s, but DO NOT wear the %s.';
out = sprintf(fmt,[X{2:end}],[Y{2:end}])
displays this string in the command window:
out = You should wear the pants and/or shoes, but DO NOT wear the scarf or heels.
There are many ways to obtained the desired output. One possible way
clothes = {'pants', 'scarf', 'heels','shoes';
true, false, true, true;
true, true, false, true};
towear = all(cell2mat(clothes([2 3], :)));
if any(towear)
%at least one item is to be worn
wornclothes = ['the ' strjoin(clothes(1, towear), ' and/or ')];
else
wornclothes = 'nothing';
end
sentence = sprintf('You should wear %s', wornclothes);
if all(towear)
%if everything has to be worn, there's no 2nd part to the sentence
sentence = [sentence '.'];
else
sentence = sprintf('%s but DO NOT wear the %s.', sentence, strjoin(clothes(1, ~towear), ' nor the '));
end
fprintf('%s\n', sentence);
The above neatly demonstrates logical indexing, all and any, and different methods of constructing strings.
Catégories
En savoir plus sur Numeric Types dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!