简体   繁体   中英

How do I put a condition into a specific column for matlab?

would like to check here on what kind of code I could use to create a specific condition on a particular column for matlab. So here is the case, I have a text file(see image),

在此处输入图片说明

with four columns of values in it. And here is the code for matlab as given below

fileID = fopen('test1.txt');
A = dlmread('test1.txt')
B = A>1000
fclose(fileID);

So according to this line of code, I have imported the file and placed them in a matrix A. Subsequently I set a condition for matrix B whereby A has to be of a greater value than 1000. Using this, I was able to get returns of '0' and '1's, which is what I wanted. Now, I want to create a set of conditions such that if column 1, 2 and 3 in any of the rows equals to 1, I will be able to display/print an output in that row that says 'Powergrip'. Apart from that condition, should 1,2 equals to 1 in any of the rows there would be a display in that row that says 'precisiongrip'? I do believe this has to do with a series of if else conditions but Im not exactly sure on how to go about writing this conditions. Please pardon my poor coding abilities as I'm really new to this. Thank you!

Firstly, you don't need the fopen() and fclose() functions when using dlmread() , just use it by itself (you only need them when you're using other functions like fread() ).

You can use the all() function to find rows (or columns) which have 1 in all columns (or rows). To find rows which contains 1 in all columns do this:

C = all(B, 2); % The "2" means work across columns.

To find cases where there's a 1 in columns 1, 2 and 3, just pass in those three columns:

C = all(B(:,[1,2,3]), 2); % PowerGrip

or for columns 1,2:

D = all(B(:,[1,2]), 2);   % PrecisionGrip

To make an array of descriptions, you need a cell array of strings. There are lots of way you could generate this, here's a simple example:

E = cell( size(C) ); % Make a cell array to hold strings, same size as C
E(:) = {'none'};     % Fill all rows with "none" to start. Could use repmat() to create E...
E(C) = {'PowerGrip'}; 
E( D & not(C) ) = {'PrecisionGrip'};

Displaying the words PowerGrip and PrecisionGrip besides the numbers is probably most easily done with a table (though you could do it a number of ways). Eg:

T = array2table(A)
T.Desc = E         % Add a column of descriptions...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM