same exact results, but without any for loops
1 次查看(过去 30 天)
显示 更早的评论
Hi, I need a help. I need the same exact results, but without any for loops. It would be a great help, if you at least give me a hint. Thanks in advance.
The code is here:
clc; clear all; close all; echo off;
key = 'matlab';
text = 'AHOJJAJSEMTVUJSUPERPOMOCNIK';
keyNums = double(key);
keySorted = zeros(1, length(key));
[c cisla] = sort(keyNums);
for i = 1:length(c)
for j = 1:length(c)
if c(i) == keyNums(j) && keySorted(j) == 0
keySorted(j) = i;
break;
end
end
end
k = 1;
l = 1;
for i = 1:size(text, 2)
M(k, l) = text(i);
l = l + 1;
if mod(i, 6) == 0
k = k+1;
l = 1;
end
end
for i=1:length(keySorted)
for j = 1:length(keySorted)
if i == keySorted(j)
cipher{i} = M(:,j)';
end
end
end
strjoin(cipher, '')
0 个评论
回答(1 个)
Deepak
2024-8-27
Hi @Tvoje Máma, from my understanding, you have a code that calculates “cipher” array as result. Now, you want to achieve the same result without using “for loops” in the code.
To do this, we can use Array manipulation and logical indexing functions in MATLAB that allows us to efficiently access, modify, and analyse the data within arrays.
To ensure the text fits perfectly into the matrix, we will utilize the “repmat()” function to create a string of space for padding. Next, we will use “reshape()” function to transform the padded text into matrix format. Finally, we will use “strttrim()” function to remove any leading or trailing spaces from the string. The “arrayfun()” helps to apply any function to each element of the array.
Attaching the documentation of methods used for reference:
Below is the complete MATLAB code that addresses this task:
clc; clear all; close all; echo off;
key = 'matlab';
text = 'AHOJJAJSEMTVUJSUPERPOMOCNIK';
keyNums = double(key);
[~, cisla] = sort(keyNums);
numRows = ceil(length(text) / length(key));
% Pad the text with spaces if necessary
paddedText = [text, repmat(' ', 1, numRows * length(key) - length(text))];
% Reshape the padded text into a matrix
M = reshape(paddedText, length(key), numRows)';
M_sorted = M(:, cisla);
% Convert sorted matrix to cell array of strings, also removing leading or trailing spaces with strtrim() method
cipher = arrayfun(@(col) strtrim(M_sorted(:, col)'), 1:size(M_sorted, 2), 'UniformOutput', false);
result = strjoin(strtrim(cipher), ' ');
disp(result);
I hope this helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!