Hi all,
Current problem: I have a 6 x 2 matrix, which looks like this:
5 0
3 0
8 2
1 2
3 2
2 2
I want to use a nested for loop with if statements to say "if 0 extract the number in the row beside" and "if 2 extract the number beside", so that I have two sets of data extracted from row 1 based on row 2's values.
Any solutions and in depth explanations especially would be great as need to get my head around these mock questions before an exam in two weeks. Thanks,
Jason.

5 Kommentare

Walter Roberson
Walter Roberson am 29 Okt. 2017
What would be the expected output for that?
Could you confirm that the 2 at the bottom of column 1 is to be treated with the same meaning as the 2s in column 2 ?
Jason Melody
Jason Melody am 30 Okt. 2017
Both columns have different meanings. They are two separate outcomes from different measures.
I want to be able to separate out column one based on column two's scores.
Geoff Hayes
Geoff Hayes am 30 Okt. 2017
Jason - why do you want to use a nested for loop? Is this part of the assignment requirement? If you are going to use a loop (and I don't think that you have to) just iterate over each element in the second column. If it is 0, then update an array for the "zero value" data. If it is 2, then update a different array for the "two value" data.
Guillaume
Guillaume am 30 Okt. 2017
I agree with Geoff. From the vague description of the desired result, I don't see the need for even one for loop and certainly can't see why you'd need nested loops. What would the inner loop iterate over?
If it's some homework problem that explicitly require the use of 2 loops, then we don't solve homework for you (that's called cheating and can get you excluded). We do provide help if you show that you made decent attempt at solving the problem and ask specific questions.
Walter Roberson
Walter Roberson am 30 Okt. 2017
I am not clear as to what "beside" here means, especially for ""if 0 extract the number in the row beside" as any given row may have up to two rows that are immediately beside the row.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Guillaume
Guillaume am 30 Okt. 2017

0 Stimmen

Using no loop at all:
M = [5 0
3 0
8 2
1 2
3 2
2 2];
[~, ~, subs] = unique(M(:, 2))
result = accumarray(subs, M(:, 1), [], @(v) {v});
celldisp(result)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 29 Okt. 2017

Kommentiert:

am 30 Okt. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by