Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

function input and output

1 Ansicht (letzte 30 Tage)
Carl Narup
Carl Narup am 5 Okt. 2017
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
Im creating a function where MPcell1 is a cell with 24 artist names of songs, unic is a cell with 11 unique artist names. I want the second row of the unic cell to add a 1 everytime unic = MPcell1 but that isn't happening. What is wrong with this?
function totsum = songsum(MPcell1, unic, c)
for i = 1:length(MPcell1)
if MPcell1(i) == unic
totsum = unic(2,c)+1;
c = c+1;
end
end
end
  1 Kommentar
James Tursa
James Tursa am 5 Okt. 2017
Every time MPcell1(i) matches any cell from the first row of unic?

Antworten (1)

Niels
Niels am 5 Okt. 2017
Hi Carl Narup,
1. u get access to the cell arrays with {}
2. if you want to compare strings use strcmp
% here is 1 solution, i am not sure if you will understand it :/ with my test strings
MPcell1 = {'a', 'e', 'q', 't', 'w', 'q', 't', 'a', 'b', 'a'};
unic = {'a', 'q', 'w'};
-------------------------
function totsum = songsum(MPcell1, unic, c)
numb_artists = length(unic); % when adding a row to unic u get a matrix, using length can be confusing then
unic(2,:) = cell(1,numb_artists); % adding a row
for i = 1:numb_artists
unic{2,i} = sum(strcmp(MPcell1,unic{1,i}));
end
end
strcmp compares all elements of MPcell1 at once with each element of unic and returns a logical array (with 1 if true and 0 if false)
sum adds up all 1s to the total number of succesfull hits
But be careful, if you are not used to use logical operations on matrices the result (or further comparisons) might surprise you.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by