how to slect random element from excel sheet?

7 views (last 30 days)
Hi..
I want to select any random element from excel sheet data for its use in a formula and i am using for loop for this. My syntax is for i=2:1:9
X1=xlsread('constant_file.xlsx',1, 'A(i)')
hold on
end
But it is showing an error
Error using xlsreadCOM (line 48) Data range is invalid.
Error in xlsread (line 230) [numericData, textData, rawData, customOutput] = xlsreadCOM(file, sheet, range, Excel, customFun);
Please do some help...
Thanx in Advance :)

Accepted Answer

dpb
dpb on 10 Jul 2014
X1=xlsread('constant_file.xlsx',1, 'A(i)')
In the above, 'A(i)' is the literal string 'A(i)', not some random cell reference. Use num2str or sprintf to build a variable string.
However instead of the overhead of opening and closing the Excel file for a single cell, I'd suggest reading the full array and then selecting from it N random entries.
x=xlsread('constant_file.xlsx'); % add fixed range that encloses the data if needed
X=x(randi([2:9],1)); % select a random value from the array
You can either repeat the above in a loop or choose the eight at one time, whichever is more convenient. If you were able to vectorize the rest of the solution the "all at once" solution might be more convenient.
An alternate way to generate the selection would be X=x(randperm(8)+1); % pull randomly from 2:9 from the array x
doc randi
doc randperm
for details.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!